所以我的模型有两个简单的关系。然后急切加载就像这样完美地工作:
Entry::with('author', 'lastModifiedBy')->...;
但是假设我想添加一个带有约束的新关系。例如:
public function foo() {
return $this->hasOne('Foo')->latest('id');
}
然后,为了急切加载这种关系,Laravel 建议这样做:
Entry::with(array('foo' => function($query) use ($id) {
$query->where('user_id', $id);
}))->...;
但如果我想包括我的author
and lastModifiedBy
关系,我最终不得不做:
Entry::with(array(
'foo' => function($query) use ($id) {
$query->where('user_id', $id);
},
'author' => function() { },
'lastModifiedBy' => function() { }
))->...;
我必须给这两个关系一个空函数。有没有一种更简单的方法来做到这一点,而不需要这些丑陋的空函数?
空函数不是必需的。 Laravel 足够聪明,能够在没有约束的情况下处理一系列混合关系。
Entry::with(array(
'foo' => function($query) use ($id) {
$query->where('user_id', $id);
},
'author',
'lastModifiedBy'
))->...;
怎么运行的
Laravel 是这样区分两者的:
in Illuminate\Database\Eloquent\Builder@parseRelations
foreach ($relations as $name => $constraints)
{
// If the "relation" value is actually a numeric key, we can assume that no
// constraints have been specified for the eager load and we'll just put
// an empty Closure with the loader so that we can treat all the same.
if (is_numeric($name))
{
$f = function() {};
list($name, $constraints) = array($constraints, $f);
}
正如注释所描述的,如果数组项的键是数字,Laravel 实际上会自行添加空闭包。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)