mercredi 2 mai 2018

Laravel nested eager loading can't work as expected

This problem has troubled me for days, I cannot solve this problem until now, so I have to ask for help.

Below is the relevant code snippet:

Model 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 Log::where([
               'product_id' => $this->newProduct()->first()->id,
               'status'     => 1,
           ])->orderBy('created_at', 'desc');
}

Controller 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 1
    dd($subCategory->find(1)->latestLog);
}

In this case, I want to use nested eager loading to get latest log. But what bothers me is when I add child.checkLatestLog it just outputs empty, but when I delete it, it will output normally.

I think the problem is related to the $this->newProduct()->first()->id variable. Because I tried to manually enter a product ID that exists in the log table, it's worked normal.

It may be my fault, but I don't know where it was wrong. I would like to thank you for asking for help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire