带有约束的 Laravel 预加载

Ric*_*kwa 0 laravel laravel-4

所以我的模型有两个简单的关系。然后急切加载完美地像这样工作:

Entry::with('author', 'lastModifiedBy')->...;
Run Code Online (Sandbox Code Playgroud)

但是说我想添加一个需要约束的新关系。例如:

public function foo() {
    return $this->hasOne('Foo')->latest('id');
}
Run Code Online (Sandbox Code Playgroud)

然后为了急切加载这种关系,Laravel 建议这样做:

Entry::with(array('foo' => function($query) use ($id) {
    $query->where('user_id', $id);
}))->...;
Run Code Online (Sandbox Code Playgroud)

但是如果我想包括我author和我的lastModifiedBy关系,我最终不得不这样做:

Entry::with(array(
    'foo' => function($query) use ($id) {
        $query->where('user_id', $id);
    },
   'author' => function() { },
   'lastModifiedBy' => function() { }
))->...;
Run Code Online (Sandbox Code Playgroud)

我必须给这两个关系一个空函数。没有这些空函数的丑陋,有没有更简单的方法来做到这一点?

luk*_*ter 5

空函数不是必需的。Laravel 足够聪明,能够处理带有约束的混合关系数组,而无需约束。

Entry::with(array(
    'foo' => function($query) use ($id) {
        $query->where('user_id', $id);
    },
    'author',
    'lastModifiedBy'
))->...;
Run Code Online (Sandbox Code Playgroud)

这个怎么运作

以下是 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);
    }
Run Code Online (Sandbox Code Playgroud)

正如评论所描述的,如果数组项的键是数字,Laravel 实际上会自己添加空闭包。