staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to get User Favorites:

Aliakbari1994 opened this issue · comments

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.

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']]
        );
    }
}

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)",

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']]
    );
}

}

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

@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');

Yes, that's correct.