使用場景
with使用在關聯模型的查詢中,支持鏈式操作
with本質
本質上是一個函數,支持一些參數
有人說是這樣的
with('模型中定義的方法名')方法
官方對with的解釋,他媽的,真惡心
看了半天,不知道with函數的參數是什么
解決辦法
只有查看with函數的源碼
如何查找with函數的原始定義位置
按道理會在think的model基類中,然而在基類model中,並沒有找到with函數的定義。
我們繼續。
最終發現 with()函數的定義在
/thinkphp/library/think/db/Query.php中
關於with的函數有三個,這時候,我們要分析函數了
分析函數的方法是,分析函數的三要素(函數名,參數,返回值),以及函數的功能。
那我們貼上和with相關的三個函數
///thinkphp/library/think/db/Query.php文件中的,2061行到2169行如下
/**
* 設置關聯查詢JOIN預查詢
* @access public
* @param string|array $with 關聯方法名稱
* @return $this
*/
public function with($with)
{
if (empty($with)) {
return $this;
}
if (is_string($with)) {
$with = explode(',', $with);
}
$first = true;
/** @var Model $class */
$class = $this->model;
foreach ($with as $key => $relation) {
$subRelation = '';
$closure = false;
if ($relation instanceof \Closure) {
// 支持閉包查詢過濾關聯條件
$closure = $relation;
$relation = $key;
$with[$key] = $key;
} elseif (is_array($relation)) {
$subRelation = $relation;
$relation = $key;
} elseif (is_string($relation) && strpos($relation, '.')) {
$with[$key] = $relation;
list($relation, $subRelation) = explode('.', $relation, 2);
}
/** @var Relation $model */
$relation = Loader::parseName($relation, 1, false);
$model = $class->$relation();
if ($model instanceof OneToOne && 0 == $model->getEagerlyType()) {
$model->eagerly($this, $relation, $subRelation, $closure, $first);
$first = false;
} elseif ($closure) {
$with[$key] = $closure;
}
}
$this->via();
if (isset($this->options['with'])) {
$this->options['with'] = array_merge($this->options['with'], $with);
} else {
$this->options['with'] = $with;
}
return $this;
}
/**
* 關聯統計
* @access public
* @param string|array $relation 關聯方法名
* @param bool $subQuery 是否使用子查詢
* @return $this
*/
public function withCount($relation, $subQuery = true)
{
if (!$subQuery) {
$this->options['with_count'] = $relation;
} else {
$relations = is_string($relation) ? explode(',', $relation) : $relation;
if (!isset($this->options['field'])) {
$this->field('*');
}
foreach ($relations as $key => $relation) {
$closure = $name = null;
if ($relation instanceof \Closure) {
$closure = $relation;
$relation = $key;
} elseif (!is_int($key)) {
$name = $relation;
$relation = $key;
}
$relation = Loader::parseName($relation, 1, false);
$count = '(' . $this->model->$relation()->getRelationCountQuery($closure, $name) . ')';
if (empty($name)) {
$name = Loader::parseName($relation) . '_count';
}
$this->field([$count => $name]);
}
}
return $this;
}
/**
* 關聯預加載中 獲取關聯指定字段值
* example:
* Model::with(['relation' => function($query){
* $query->withField("id,name");
* }])
*
* @param string | array $field 指定獲取的字段
* @return $this
*/
public function withField($field)
{
$this->options['with_field'] = $field;
return $this;
}
但是,源碼,我也是沒看懂!擦!
繼續,看看別人網友的使用方法
問題:多對多模型,能使用with函數嗎
參考文章
TP5.1多對多關聯添加查詢條件
https://blog.csdn.net/weixin_39429350/article/details/98599169
看來,with函數,不支持多對多模型的查詢