'How get conditional nested relationship of parent polymorphic relationship in laravel Eloquent?
$share2 = Share::with(['Post' => function($query){
$query->with(['Postable']);
}])
->whereHas('Post',function ($query){
$query->when('postable_type' == App\Models\User,function ($query){
$query->whereHas('Postable',function ($query){
$query->whereHas('Follower',function ($query){
$query->where('user_id', auth()->check() ? auth()->user()->id : null);
});
});
})->when('postable_type' == App\Models\Agency ,function ($query){
$query->whereHas('Friend', function ($query) {
$query->where('mirror_user_id', auth()->user()->id);
$query->where('status', 'friend');
});
});
// I have used when but it seems useless for my case
})
->where('shareable_type', 'App\Models\User')
->where('shareable_id', auth()->user()->id)
->orWhere('shareable_type', 'App\Models\Agency')
->orWhere('shareable_id', 1)
->get();
I have a polymorphic relationship (Postable) on Post model, Postable return either Agency model or User model, then from Postable I want get Follower if the Postable was App\Models\Agency, or get Friend if the Postable was App\Models\User, my User has not Follower relationship because it is for Agency model, instead User has Friend relationship that Agency has not. now I want to check if the Postable was App\Models\Agency then return Follower relationship if it was User then return Friend.
relationships structure:
Share -> Post -> Postable(Agency,User)
Agency->Follower
User->Friend
hope I my explanation will take place in your mind
thanks in advance
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
