如何通过急切加载仅访问相关模型

I have these models in my project:

class User {

    public function favorites()
    {
        return $this->hasMany('App\Favorite');
    }

}

-

class Product {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

}

-

class Favorite {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function product()
    {
        return $this->belongsTo('App\Product');
    }

}


When I try to get the user's favorites i will do like this:-

$user = User::find(1);
return $user->favorites;

Or with the products in his favorites:-

return $user->favorites->load('product');

But It returns the results from both (products and favorites).

How do I get the results only from Product model through the Favorite?

Like I want to retrieve only the products that the user added to his favorites?

I already tried to make this in the User class and it doesn't work:-

public function favproducts()
{
    return this->hasManyThrough('App\Product', 'App\Favorite');
}


Thank you in advance.

This seems like this could be a belongsToMany between User and Product to make a 'favorites', as the pivot table.

Your current setup is missing the inverse relationship from Product to Favorite, so you can't use the relationship in that direction. Which is the direction I would use to get the result you want.

If you had the relationship setup, you could potentially do this to just get the Products for a User's favorites.

Product::whereHas('favorites.user', function ($q) use ($user_id) {
    $q->where('id', $user_id);
})->get();

Get all products that have a favorite that is for user with id == $user_id.

If this was setup for a belongsToMany you could potentially just do this instead:

User::find($id)->favorites;

With what you currently have, you could "fetch" the children records out of the result you have on the PHP side.

Try:

$user->favorites->product['name']

try this: in your case, i think it is a Nested Eager Loading

$user = User::with('favorites.product')->get();
//to grab the data
dd($user->favorites[0]->product);

hope it is help