Laravel具有条件并渴望加载

lka*_*ono 5 belongs-to eager-loading laravel

我有一个与Section模型相关的Post模型,这取决于工作的额外条件:

<?php
class Post extends Base
{
    public function section()
    {
        return $this->belongsTo('App\Models\Section', 'id_cat')->where('website', $this->website);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我想检索帖子并获取它的关联部分时,可以按照以下方式进行操作:

$post = Post::first();
echo $post->section->name; // Output the section's name
Run Code Online (Sandbox Code Playgroud)

但是,当尝试使用急切的负载获取该部分时:

Post::with(['section'])->chunk(1000, function ($posts) {
    echo $post->section->name;
});
Run Code Online (Sandbox Code Playgroud)

Laravel抛出以下异常:

PHP error:  Trying to get property of non-object
Run Code Online (Sandbox Code Playgroud)

当我对上述热切的加载查询返回的Post对象进行调试时,我注意到该section关系为null。请注意,如果我从belongsTo关联中删除条件,则它工作正常。

你们有什么想法为什么会发生吗?

Vis*_*rma 3

正如我的评论中提到的,where不应在关系定义中使用。因此,您的关系定义只需

public function section()
{
    return $this->belongsTo('App\Models\Section', 'id_cat');
}
Run Code Online (Sandbox Code Playgroud)

并且您可以以这种方式急切加载(不给出带有块等的确切查询)

Post::with(['section' => function ($query) use ($request) {
    $query->where('website', $request['website'])
}])->get()->first();
Run Code Online (Sandbox Code Playgroud)

即当您在请求中传递变量website或以类似的方式使用任何其他变量时。

我希望这能解释。如果还有什么不清楚的地方欢迎大家补充。