0

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?

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

that's the right answer, thank you. Huge thanks also for @acabala for his help for solving this issue +1
2

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);

14 Comments

thank you for your answer, but I'm not familiar with manual joining multiple tables (there I have pivot table offer_speciality) and when I've got model already configured, I want to use it...
then try something like this one: $offers = Offer::with('specialities')->when($speciality, function($query, $speciality) { return $query->where('speciality_name', $speciality)->get(); })->orderBy('created_at','desc')->paginate(9); (adding with to your primary query).
this gives me unknown collumn (after added with('specialities'))
Is speciality_name correct column name? Maybe you have just name, so then it will be speciality.name
I'm putting the correct column name, and it seems that this with('specialities') solution does not work
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.