In my case I have channels table that is in many to many relation with categories table.
I want to fetch the channels that their categories contain a dynamic value like doing LIKE query on title of each category. but I need to check another columns of a channel by where clause.
This is a channel structure:
[
{
"id": 87,
"username": "ch1",
"title": "ch title",
"type": "channel",
"members": 210424,
"location": "tabriz",
"created_at": "2017-05-09 01:39:44",
"updated_at": "2017-05-16 17:19:28",
}
]
To get what I want I run this query:
$channels = Channel::orderBy('members', 'desc')
->whereHas('categories', function ($query) use ($category) {
$query->where('title', 'LIKE', '%' . $category . '%');
})
->where([
['visible', 1],
['title', 'LIKE', '%' . $trend . '%'],
['location', 'LIKE', '%' . $location . '%'],
['members', '>', $members]])
->get();
Upper query return me all the channels like a query without whereHas clause whiles when I use 'whereHas' alone, it return channels with in category that I want!
Am I use wrong syntax? Is it true to use where and whereHas clauses side by side?
UPDATE:
I need do like query on channel's title or username, so I use orWhere but the result is as before! it returns all channels to me! like query without whereHas again.
So I use this query to do it,
$channels = Channel::orderBy('members', 'desc')
->whereHas('categories', function ($query) use ($category) {
$query->where('title', 'LIKE', '%' . $category . '%');
})
->where([
['visible', 1],
['title', 'LIKE', '%' . $trend . '%'],
['location', 'LIKE', '%' . $location . '%'],
['members', '>', $members]])
->orWhere([
['visible', 1],
['username', 'LIKE', '%' . $trend . '%'],
['location', 'LIKE', '%' . $location . '%'],
['members', '>', $members]])
->get();
At first I thought the problem is orderBy clause as @exprator sayed, but after adding orWhere I understood that orderBy is not my issue.
Channel::whereHas('categories', function ($query) use ($category) {
$query->where('title', 'LIKE', '%' . $category . '%');
})->orderBy('members', 'desc')
use the whereHas before the order_by
->orWhere(function ($query) {
$query->where('visible', '=', 1)
->where('username', 'LIKE', '%' . $trend . '%')
->where('location', 'LIKE', '%' . $location . '%')
->where('members', '>', $members);
})
Try to just use ->whereHas() after the ->where(). You don't need to duplicate anything normally.
$channels = Channel::where([
['visible', 1],
['title', 'LIKE', '%' . $trend . '%'],
['location', 'LIKE', '%' . $location . '%'],
['members', '>', $members]])
->orWhere([
['visible', 1],
['username', 'LIKE', '%' . $trend . '%'],
['location', 'LIKE', '%' . $location . '%'],
['members', '>', $members]])
->whereHas('categories', function ($query) use ($category) {
$query->where('title', 'LIKE', '%' . $category . '%');
})
->orderBy('members', 'desc')
->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With