Reputation: 878
Follow is my query which is working perfectly fine, it is giving me the expected result, but i am not happy with the way i have broken down the query in 3 pieces. How can i combine this query like without breaking it down in pieces ?
$assignedMenusQuery = Branch::with(['menus' => function($query) {
$query->where('menus.status', true);
}])
->where('id', $branch->id)
->first();
if($assignedMenusQuery)
{
$assignedMenus = $assignedMenusQuery->menus->pluck('id')->toArray();
}
$assignedButSharedMenusQuery = Branch::with(['menus' => function($query) {
$query->where('menus.shared', true)
->where('menus.status', true);
}])
->whereNotIn('id', [$branch->id])
->first();
if($assignedButSharedMenusQuery)
{
$assignedButSharedMenus = $assignedButSharedMenusQuery->menus->pluck('id')->toArray();
}
$assignedButNotSharedMenusQuery = Branch::with(['menus' => function($query) {
$query->where('menus.shared', false)
->where('menus.status', true);
}])
->whereNotIn('id', [$branch->id])
->first();
if($assignedButNotSharedMenusQuery)
{
$assignedButNotSharedMenus = $assignedButNotSharedMenusQuery->menus->pluck('id')->toArray();
}
$menus = Menu::whereIn('id', array_merge($assignedMenus, $assignedButSharedMenus))->whereNotIn('id', $assignedButNotSharedMenus)->get();
Upvotes: 0
Views: 83
Reputation: 878
Here is how i did it, in case if someone needs it in future
$products = Product::whereNotIn('id', function($query) use($menu) {
$query->from('menu_product')
->select('menu_product.product_id');
})
->orWhereIn('id', function($query) {
$query->from('menu_product')
->select('menu_product.product_id')
->where('products.shared', true);
})
->orWhereIn('id', function($query) use($menu) {
$query->from('menu_product')
->select('menu_product.product_id')
->where('menu_product.menu_id', $menu->id);
})
->get();
Upvotes: 0
Reputation: 1050
Here what you can do this make a seperate function which accepts a parameter for shared
& status
. And other param for whereNotIn
. And in that function you can use the when
method and based on that you have to query in database.
Upvotes: 1