ChristianKuri / laravel-favorite

Allows Laravel Eloquent models to implement a 'favorite', 'like', 'remember' and 'follow' features.
MIT License
226 stars 48 forks source link

Eager load user's favourite models #15

Closed romansidorov closed 5 years ago

romansidorov commented 5 years ago

Hi there!

I get user's favourite models: $user->favorite(Material::class); But it produces many similar db-queries: https://take.ms/fuKu3

How could I eager load that?

Thanks!

ChristianKuri commented 5 years ago

Have to tried this?

Something like $user->load('favorites.material') Or you could also add $with = ['favorites.material']; to your user model

if it doesnt work use materials or something like that, im not sure how you named the relationship

romansidorov commented 4 years ago

Have to tried this?

Something like $user->load('favorites.material') Or you could also add $with = ['favorites.material']; to your user model

if it doesnt work use materials or something like that, im not sure how you named the relationship

Yes, I tried but had no effect and caught Call to undefined relationship [material] on model [ChristianKuri\LaravelFavorite\Models\Favorite]. error. Why should it work? Where this relationship (favorites.material) been declared?

tpaksu commented 3 years ago

@romansidorov, I found an easy way to do that:

Create a favorite materials relationship method in your User class:

public function favoriteMaterials(){
    return $this->favorites()->where("favoriteable_type", "=", \App\Material::class);
}

then load that instead:

$user->load("favoriteMaterials");

// or when building the query
$users = \App\User::with("favoriteMaterials");