Laravel Eloquent, apply select on my queries in whereHas - php

Here my code :
$prestations = Prestation::with('service','facility','conciergeries.network')
->whereHas('service', function ($query) use ($searchService) {
$query->addSelect('id','name')->where('name', 'regexp', "/$searchService/i");
})
->whereHas('facility', function ($query) use ($searchPartenaire) {
$query->addSelect('id','name')->where('name', 'regexp', "/$searchPartenaire/i");
})
->whereHas('conciergeries.network', function ($query) use ($searchFiliale) {
$query->addSelect('id','name')->where('name', 'regexp', "/$searchFiliale/i");
})
->where('name', 'regexp', "/$search/i")
->orderBy($orderBy, $orderDirection)
->paginate(50);
I want get only names and ids of "service", "facility" and "conciegeries.network".
I tried to use select('id','name'); and select(['id','name']); or addSelect('id','name'); and pluck('id', 'name'); but i get all datas.
Do you have alternatives solutions ?
Thank you !

Select needs to be added to with, not whereHas. Try this instead:
Prestation::with(['service' => function($query) { $query->select(['id','name']);},
'facility' => function($query) { $query->select(['id','name']);},
'conciergeries.network' => function($query) { $query->select(['id','name']);}
])

Related

check condition within query in laravel

$q = Order::select(
'orders.*',
'items.date_start',
'items.date_end',
'items.location_name',
'items.category_id'
)
->join('items', 'items.item_id', '=', 'orders.item_id')
->leftJoin('orders_items', function ($join) use ($user_id)
{
$join->on('orders_items.order_id', '=', 'orders.order_id')
->on('orders_items.item_id', '=', 'orders.item_id')
->where('orders_items.user_id', '=', $user_id);
})
->with('Items')
->where(function ($query) use ($select_balance) { // This is where event is in the future, or it has a balance and is not draft.
$query->where('items.date_end', '>=', Carbon\Carbon::now()->toDateString())
->orWhere(function ($query) use ($select_balance) {
$query->where(DB::raw($select_balance), '>', 0)
->whereNotIn('orders.status', [0, 79]);
});
});
i would like to set a condition if (date_start == date_end) then
$query->where('items.date_end', '>=', Carbon\Carbon::now()->toDateString())
->orWhere(function ($query) use ($select_balance) {
$query->where(DB::raw($select_balance), '>', 0)
->whereNotIn('orders.status', [0, 79]);
});
else
$query->where('items.date_end', '>', Carbon\Carbon::now()->toDateString())
->orWhere(function ($query) use ($select_balance) {
$query->where(DB::raw($select_balance), '>', 0)
->whereNotIn('orders.status', [0, 79]);
});
how to set a condition within query i try to end query after ->with(items) but that say $q-> has syntax error please guide and explain how to over come this issue
You can use conditional clauses: https://laravel.com/docs/5.5/queries#conditional-clauses
Animals::when($condition, function($query) {
$query->where('size', 'big');
})->when(!$condition, function($query)) {
$query->where('size', 'small');
})->get();
In the example, if $condition is true then we fetch big animals, otherwise we fetch small animals.

Laravel/Eloquent: Add missing () in sql statements generated by eloquent

I am doing the following request to extract some data from my database. The expected result is wrong because some parenthesis is not well placed in the SQL generated request:
$data = Ov::with([
'masters' => function ($query) use ($devicesArrayOnlyLKUAToZero) {
$query->whereIn('macAddress', $devicesArrayOnlyLKUAToZero)
->orWhere('lastKnownUpAt','<>', '0');
}
])->where('ovId', '=', $ovId)->get();
The dedicated sql generated by Laravel is: (see with Laravel debugbar):
select * from `masterequipments` where `masterequipments`.`id_ov_foreign_key` in ('38') and `macAddress` in ('e8:e7:32:c1:e6:48', 'e8:e7:32:bc:b0:94', 'e8:e7:32:e4:8e:68', 'e8:e7:32:bc:a7:70', '00:e0:b1:fe:ef:a5', 'e8:e7:32:bc:a7:a4', '2c:fa:a2:10:79:74', 'e8:e7:32:b9:6d:1d', '00:e0:b1:ee:58:2d', '00:e0:b1:9d:2c:44', '00:e0:b1:b5:e6:00', '00:e0:b1:72:34:86', '00:e0:b1:fe:ee:8d', '00:e0:b1:79:53:52', '00:e0:b1:fe:f0:bd', '00:e0:b1:75:fa:8a', 'e8:e7:32:98:80:22', '00:e0:b1:75:00:8a') or `lastKnownUpAt` <> '0'
This is wrong because 2 () are missed. I would like to have:
select * from `masterequipments` where `masterequipments`.`id_ov_foreign_key` in ('38') and (`macAddress` in ('e8:e7:32:c1:e6:48', 'e8:e7:32:bc:b0:94', 'e8:e7:32:e4:8e:68', 'e8:e7:32:bc:a7:70', '00:e0:b1:fe:ef:a5', 'e8:e7:32:bc:a7:a4', '2c:fa:a2:10:79:74', 'e8:e7:32:b9:6d:1d', '00:e0:b1:ee:58:2d', '00:e0:b1:9d:2c:44', '00:e0:b1:b5:e6:00', '00:e0:b1:72:34:86', '00:e0:b1:fe:ee:8d', '00:e0:b1:79:53:52', '00:e0:b1:fe:f0:bd', '00:e0:b1:75:fa:8a', 'e8:e7:32:98:80:22', '00:e0:b1:75:00:8a') or `lastKnownUpAt` <> '0')
Use advanced where clauses to accomplish it.
$data = Ov::with([
'masters' => function ($query) use ($devicesArrayOnlyLKUAToZero) {
$query->where(function ($query) use ($devicesArrayOnlyLKUAToZero) {
$query->whereIn('macAddress', $devicesArrayOnlyLKUAToZero);
})
->orWhere(function($query) {
$query->where('lastKnownUpAt','<>', '0');
});
}
])->where('ovId', '=', $ovId)->get();
UPDATE
$data = Ov::with([
'masters' => function ($query) use ($devicesArrayOnlyLKUAToZero) {
$query->where(function ($query) use ($devicesArrayOnlyLKUAToZero) {
$query->whereIn('macAddress', $devicesArrayOnlyLKUAToZero);
})
->orWhere('lastKnownUpAt','<>', '0');
}
])->where('ovId', '=', $ovId)->get();
Yo need to do something like this:
$data = Ov::with([
'masters' => function ($query) use ($devicesArrayOnlyLKUAToZero) {
$query->where(function ($query) use ($devicesArrayOnlyLKUAToZero) {
$query->whereIn('macAddress', $devicesArrayOnlyLKUAToZero);
})
->orWhere(function($query) {
$query->where('lastKnownUpAt','<>', '0');
});
}
])->where('ovId', '=', $ovId)->get();
This article explain it well http://laraveldaily.com/and-or-and-brackets-with-eloquent/

How to add bracket in laravel query builder using 'WHEN' condition?

Given this code:
$objResellerList - DB::table('ResellerMaster as RM')
->leftJoin('StateMaster as SM','SM.id',RM.id_StateMaster')
->leftJoin('RegionMaster as REM','REM.id','=','RM.id_RegionMaster')
->leftJoin('DealerGroupMaster as DGM','DGM.id','=','RM.id_DealerGroupMaster')
->when($keywords, function($query) use ($keywords) {
return $query->where('RM.company_name', 'like', '%'.$keywords.'%')
->orWhere('DGM.name', 'like', '%'.$keywords.'%')
->orWhere('RM.email', 'like', '%'.$keywords.'%')
->orWhere('RM.pic', 'like', '%'.$keywords.'%')
->orWhere('RM.pic_mobile_no', 'like', '%'.$keywords.'%');
})
->when($status, function($query) use ($status) {
return $query->where('RM.status', $status);
})
->select('RM.*','SM.name as state','REM.name as region', 'DGM.name as dealer_group')
->orderby('RM.company_name','asc')
->paginate(10);
When i search with keywords, I need to close it with a bracket at when condition. How to include the bracket at when condition?
DB::table('users')
->where('name', '=', 'John')
->orWhere(function ($query) {
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
give u brackets
select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
so use where with function
->orWhere(function ($query) {
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
or
->where(function ($query) {
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
it will give u brackets
use
->when($status,function($query) {
return $query->where(function ($query) {
//do some action
})
})

laravel query join with only latest record

I'm using Laravel 5.3 and trying to return a heist with it's product and only the latest order and with the latest price history. Both joins don't return anything but if I remove the $q->latest()->first(); and replace it with a simple orderBy() I get all results. My query is:
$data = $heist->with(['product'=> function($query) {
$query->with(['orders' => function($q) {
return $q->latest()->first();
}]);
$query->with(['price_history' => function($q) {
return $q->latest()->first();
}]);
}])->orderBy('completed_at', 'DESC')->orderBy('active', 'DESC')->get();
As discussed in the comments, I believe the simplest way of doing this is
$heists = $heist->with(['product'=> function($query) {
$query->with([
'orders' => function($q) {
return $q->orderBy('created_at', 'desc')->take(1)->get();
},
'price_history' => function($q) {
return $q->orderBy('created_at', 'desc')->take(1)->get();
}
]);
}])->orderBy('completed_at', 'desc')->orderBy('active', 'desc')->get();
Hope this helps :)
Calling first() is the same as calling take(1)->get()[0];
Which means limit the amount returned to 1 and return it. What you want is just the limit part. So if you change first() to take(1).
Update
$data = $heist->with([
'product'=> function($query) {
$query->with(
[
'orders' => function($q) {
$q->latest()->take(1);
},
'price_history' => function($q) {
$q->latest()->take(1);
}
]
);
}
])->orderBy('completed_at', 'DESC')->orderBy('active', 'DESC')->get();

Laravel Relationsship laod

$jobs = EventJob::with(['applications' => function ($query) {
$query->where('accepted', false);
}, 'job' => function($query) {
$query->where('division_id', 1);
}, 'event' => function($query) use ($date) {
$query->where('date', '>=', $date);
}])->get();
Complete overhaul of the question.
I wan't only the EventJob elements where the conditions in the $query are true but I get all the elements.
Seems like the function you're looking for is whereHas, it is documented here.
Your code would then be :
$jobs = EventJob::whereHas('applications', function ($query) {
$query->where('accepted', false);
})->whereHas('job', function($query) {
$query->where('division_id', 1);
})->wherehas('event', function($query) use ($date) {
$query->where('date', '>=', $date);
})->get();

Categories