Closed Aliakbari1994 closed 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']]
);
}
}
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.
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.