Hey all!
My database call looks like this essentially:
$questions = \App\ContentLegacy::with('staff', 'meta', 'questionStandards')->where('post_type','nm_question')->orderBy("post_date", "DES")->paginate(20);
This call works just great. However, I want to be able to narrow this search even further based off of information in the 'meta' table. So, in my hopeful ignorance, I wrote out the following broken query...
$questions = \App\ContentLegacy::with('staff', 'meta', 'questionStandards')->where('post_type','nm_question')->where('meta', ['meta_key' => 'flagged'])->orderBy("post_date", "DES")->paginate(20);
Does that make sense? Basically, I want to collect only the objects if their associated meta table has a key/value pair of 'meta_key' and 'flagged'.
I've been fighting eloquent for a while and haven't found too much useful. I can just query for all of the questions and filter with my own code. But that will mess up the pagination. And then I'll have to write my own pagination. These are things I'd like to understandably avoid.
Any help would be swell.
I think the method you're looking for is whereHas
(under the heading "Querying Relationship Existence").
$questions = \App\ContentLegacy::with('staff', 'meta', 'questionStandards')
->where('post_type','nm_question')
->whereHas('meta', function ($query) {
$query->where('meta_key', 'flagged');
})
->orderBy("post_date", "DES")
->paginate(20);
The has
method can take a callback argument too, but in this case that would be more verbose.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community