gravicle
gravicle

Reputation: 324

How do I perform a join in Laravel 5 with a `where` clause?

I have a table, offers, with purchases which has an id for the purchased item. The item is stored in another table, items. In response to a GET request, I want to return the full item object with purchases. How do I go about doing this?

public function getBuys(Request $request)
{
    $usr_id = $request->input('usrid');

    $buys = Offer::where('buyer_id', '=', $usr_id)->get();
    return response()->json($buys);
}

Upvotes: 1

Views: 900

Answers (1)

Pawel Bieszczad
Pawel Bieszczad

Reputation: 13325

Right now you are getting all the offer(purchases) made by a user correct? If you want to get a specific item with all offers (assuming you have realtionship set in your item model):

$item = Item::->with('offers')->find($itemId);

EDIT If you have this relation in you Offer model:

public function item()
{
    return $this->hasOne('App\Item');
}

you can just do this:

$buys = Offer::with('item')->where('buyer_id', '=', $usr_id)->get();

Upvotes: 1

Related Questions