gileneusz
gileneusz

Reputation: 1485

Laravel query using existing model

I've got two models: Offers and Speciality with many to many relatioship:

in Offer.php

public function specialities()
{
    return $this->belongsToMany('App\Speciality');
}

in Speciality.php

public function offers()
{
    return $this->belongsToMany(Offer::class);
}

this is simple so far.

Now, I'm building query to get only Offers with certain speciality. The problem is that I'm using when helper function, so I don't know how to access speciality model:

public function template($person = "", $speciality = "")
{
      $offers = Offer::when($speciality, function($query, $speciality) {
        return $query->specialities()->where('speciality_name', $speciality)->get();
      })->orderBy('created_at','desc')->paginate(9);
}

And this is not working for me. Can anyone give me a tip how should I write it?

Upvotes: 0

Views: 284

Answers (2)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Use whereHas():

$offers = Offer::when($speciality, function($query, $speciality) {
    $query->whereHas('specialities', function($query) use($speciality) {
        $query->where('speciality_name', $speciality);
    });
})->orderBy('created_at', 'desc')->paginate(9);

Upvotes: 3

acabala
acabala

Reputation: 149

For querying you should use join instead specialities() relation, so it will look more like:

 $offers = Offer:join('offer_specialities os', 'offer.id', 'os.offer_id')
 ->join('specialities', 'specialities.id', 'os.speciality_id')
 ->when($speciality, function($query, $speciality) {
    return $query->where('specialities.speciality_name', $speciality)->get();
  })->orderBy('created_at','desc')->paginate(9);

Upvotes: 2

Related Questions