Reputation: 15
I have a table called List which i planned to be displayed into view with this command : $lists= List::with('user', 'product.photodb', 'tagCloud.tagDetail')->get();
. But, i want the data displayed is only those that has TagID equal to the one user inputted. Those data can be retrieved from TagCloud table.
What i am currently doing is :
$clouds = TagCloud::select('contentID')
->where('tagDetailID', '=', $tagID)
->get();
$lists = List::with('user', 'product.photodb', 'tagCloud.tagDetail')
->where('id', '=', $clouds->contentID)
->get();
But when i tried to run it, it only return a null value, even though when i am doing return $clouds
, it does returned the desired ID.
Where did i do wrong ? Any help is appreciated !
Upvotes: 0
Views: 1145
Reputation: 774
Apply Where condition in you tagCloud model method tagDetail
public function tagDetail(){
return $q->where('id', $id);
}
Upvotes: 0
Reputation: 12872
What you want is whereHas()
$list = List::with(...)
->whereHas('relation', function($q) use($id) {
return $q->where('id', $id);
})->get();
Upvotes: 0
Reputation: 5791
A couple of gotchas with your current solution.
get()
returns an Illuminate\Database\Eloquent\Collection
object. Hence you can't use $clouds->contentID
directly since $clouds
is a collection (or array if you prefer). See Collection Documentation.where(...)
expects the third parameter to be a string or integer, aka single value. Instead, you are passing a collection
, which won't work.The correct way is to use whereHas()
which allows you to filter through an eager loaded relationship.
Final Code:
$lists = List::with('user', 'product.photodb', 'tagCloud.tagDetail')
->whereHas('tagCloud',function($query) use ($tagID) {
return $query->where('contentID','=',$tagID);
})
->get();
Upvotes: 1