thinkphp5的with函数使⽤场景
with使⽤在关联模型的查询中,⽀持链式操作
with本质merge函数
本质上是⼀个函数,⽀持⼀些参数
有⼈说是这样的
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多对多关联添加查询条件
看来,with函数,不⽀持多对多模型的查询
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论