thinkphp5的with函数使⽤场景
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 = fal;
if ($relation instanceof \Closure) {
// ⽀持闭包查询过滤关联条件
$closure = $relation;
$relation = $key;
$with[$key] = $key;
} elif (is_array($relation)) {
$subRelation = $relation;
$relation = $key;
} elif (is_string($relation) && strpos($relation, '.')) {
$with[$key] = $relation;
list($relation, $subRelation) = explode('.', $relation, 2);
}
/** @var Relation $model */
$relation = Loader::parName($relation, 1, fal);anyconnect
中国排名大学$model = $class->$relation();
七年级下册语文书古诗if ($model instanceof OneToOne && 0 == $model->getEagerlyType()) {
$model->eagerly($this, $relation, $subRelation, $closure, $first);
武汉光谷步行街
$first = fal;
} elif ($closure) {
$with[$key] = $closure;
脑中风后遗症}
}
$this->via();
if (ist($this->options['with'])) {
$this->options['with'] = array_merge($this->options['with'], $with);
} el {
$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;静字
} el {
$relations = is_string($relation) ? explode(',', $relation) : $relation;
if (!ist($this->options['field'])) {
$this->field('*');
}
foreach ($relations as $key => $relation) {
$closure = $name = null;
if ($relation instanceof \Closure) {
$closure = $relation;
$relation = $key;
} elif (!is_int($key)) {
$name = $relation;
$relation = $key;
}
$relation = Loader::parName($relation, 1, fal);
$count = '(' . $this->model->$relation()->getRelationCountQuery($closure, $name) . ')'; if (empty($name)) {
$name = Loader::parName($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多对多关联添加查询条件
看来,with函数,不⽀持多对多模型的查询