所以我的模型有两个简单的关系。然后,渴望加载就像这样:
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
和lastModifiedBy
关系,我最终必须这样做:
Entry::with(array(
'foo' => function($query) use ($id) {
$query->where('user_id', $id);
},
'author' => function() { },
'lastModifiedBy' => function() { }
))->...;
我必须给这两个关系一个空函数。如果没有这些空函数的丑陋,有没有更简单的方法呢?
答案 0 :(得分:2)
不需要空函数。 Laravel非常聪明,能够处理一系列具有约束条件的混合关系,而且没有它们。
Entry::with(array(
'foo' => function($query) use ($id) {
$query->where('user_id', $id);
},
'author',
'lastModifiedBy'
))->...;
以下是Laravel如何区分两者:
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实际上会自己添加空闭包。
答案 1 :(得分:0)
你不需要那些空功能。你可以直接把关系放在它们上面。
Entry::with(array(
'foo' => function($query) use ($id) {
$query->where('user_id', $id);
},
'author', 'lastModifiedBy'
))->...;
或者你也可以把它们与方法嵌套。
Entry::with(array(
'foo' => function($query) use ($id) {
$query->where('user_id', $id);
}
))
->with('author', 'lastModifiedBy')->...;