staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

How to get User Favorites: #173

Closed Aliakbari1994 closed 2 years ago

Aliakbari1994 commented 2 years ago

Hello, How to get User Favorites:

[User] --> HasMany --> [Favorite] --> MorphTo --> [Post, Video, Image]

Favorite Table: user_id, favoritable_type, favoritable_id

I need a relation to get user favorite posts in user model.

staudenmeir commented 2 years ago

Hi @Aliakbari1994,

Use this relationship:

class User extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function favoritePosts()
    {
        return $this->hasManyDeep(
            Post::class,
            [Favorite::class, 'favoritables'],
            [null, null, 'id'],
            [null, null, ['favoritable_type', 'favoritable_id']]
        );
    }
}
Aliakbari1994 commented 2 years ago

Hi @staudenmeir thanks; im get this error: "message": "SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'favoritables' (SQL: select count(*) as aggregate from posts inner join favoritables on favoritables.favoritable_id = posts.id inner join favoritables on favoritables.id = favoritables.favoritable_id where favorites.favoritable_type = App\Post and favorites.user_id = 8 and posts.deleted_at is null)",

Aliakbari1994 commented 2 years ago

this is ok: class User extends Model { use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

public function favoritePosts()
{
    return $this->hasManyDeep(
        Post::class,
        [Favorite::class],
        [null, null, 'id'],
        [null, null, ['favoritable_type', 'favoritable_id']]
    );
}

}

staudenmeir commented 2 years ago

Ah, I thought there's an additional level. Is your issue solved?

Aliakbari1994 commented 2 years ago

@staudenmeir Yes, my problem is solved. The question is, how can I sort the received records based on the favoritables table? is it correct?

return $this->hasManyDeep( Post::class, [Favorite::class], [null, null, 'id'], [null, null, ['favoritable_type', 'favoritable_id']] )->latest('favoritables.id');

staudenmeir commented 2 years ago

Yes, that's correct.