There are several ways to achieve the same.
$wanted = Posting::where('user_id', '=', $user_id)->whereHas('offers', function($offerQuery){
$offerQuery->where('id', '=', $offer_id);
})->get();
You probably do some manipulation with the user
$user = User::find($user_id);
$wanted = $user->postings()->whereHas('offers', function($offerQuery){
$offerQuery->where('id', '=', $offer_id);
})->get();
Or you inspect the offer
$offer= Offer::find($offer_id);
$wanted = $offer->postings()->where('user_id', '=', $user_id)->get();
Or you make @Firtzberg's last example into one query:
$wanted = $offer->where('offer_id', $offer_id)->postings()->where('user_id', '=', $user_id)->get();
I think, loading the images should work with ->with('images')
:
$wanted = $offer->where('offer_id', $offer_id)->postings()->where('user_id', '=', $user_id)->with('images')->get();
Somehow, this forum doesn't let me edit the previous posts, so here goes the corrected version:
$wanted = Offer::where('offer_id', $offer_id)->postings()->where('user_id', '=', $user_id)->with('images')->get();
Thanks a lot for everyone's help. The only change I had to make was adding ->first() so an object was returned rather than a collection.
$wanted = Offer::where('offer_id', $offer_id)->first()->postings()->where('user_id', '=', $user_id)->with('images')->get();
This is a useful thread! Can anyone run this same example using morphedbymany relationship between Offers and Postings? I believe it should look almost identical except that eloquent will know to query the morph tables and join results.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community