Laravel 5 Laravel嵌套式紧急加载罐';I don’我没有按预期工作

Laravel 5 Laravel嵌套式紧急加载罐';I don’我没有按预期工作,laravel-5,eloquent,laravel-5.4,Laravel 5,Eloquent,Laravel 5.4,这个问题困扰了我好几天,我现在还不能解决这个问题,所以我不得不寻求帮助 以下是相关的代码片段: 模型Category.php public function child() { return $this->hasMany('App\Http\Models\Category', 'pid', 'id'); } public function logs() { return $this->hasMany('App\Http\Models\Log', 'cate_id')

这个问题困扰了我好几天,我现在还不能解决这个问题,所以我不得不寻求帮助

以下是相关的代码片段:

模型Category.php

public function child()
{
    return $this->hasMany('App\Http\Models\Category', 'pid', 'id');
}

public function logs()
{
    return $this->hasMany('App\Http\Models\Log', 'cate_id');
}

public function products()
{
    return $this->hasMany('App\Http\Models\Product', 'cate_id');
}

public function newProduct()
{
    return $this->products()->orderBy('created_at', 'desc');
}

public function latestLog()
{
    return $this->logs()->where([
               'product_id' => $this->newProduct()->first()->id,
               'status'     => 1,
           ])->orderBy('created_at', 'desc');
}
控制器CategoryController.php

public function getLatestLog()
{
    // Category with id 1 with nested eager loading
    $subCategory = Category::find(1)
                   ->with(['child.newProduct', 'child.latestLog'])
                   ->first()->child;

    // Get latest log for subCategory with id 3
    dd($subCategory->find(3)->latestLog);
}
在这种情况下,我想使用嵌套的即时加载来获取最新的日志。但困扰我的是,当我添加
child.checkLatestLog时,它只输出空的,但当我删除它时,它将正常输出

我认为问题与
$this->newProduct()->first()->id
变量有关。因为我试图手动输入日志表中存在的产品ID,所以工作正常

这可能是我的错,但我不知道哪里错了。我要感谢你的帮助


更新

这个问题的解决办法是:

public function latestLog()
{
    return $this->hasManyThrough(
        'App\Http\Models\Log',
        'App\Http\Models\Product',
        'cate_id',
        'product_id',
        'id',
        'id'
    )->orderBy('created_at', 'desc');
}

问题是
$this->newProduct()->first()->id
:您不能对依赖于模型的属性使用即时加载


您必须使用加入解决方案。

latestLog
必须是一种关系。@JonasStaudenmeir感谢您的回复!我将函数
latestLog()
更改为一个关系
$this->logs()->where([…])
,但仍然无法得到预期的结果。您可以尝试
$this->newProduct->first()->id
而不是
$this->newProduct()->first()->id
我的意思是删除()符号。@MakashovNurbol谢谢您的建议,但它没有效果。