Laravel Eloquent : with query parameters
30,677
Solution 1
Worked it out if anyone has same problem... need to use use
statement
$campaign = Campaign::find($campaign_id);
$buyers = $campaign->buyers()->with('notes')->with(['emails' => function($q) use ($campaign_id){
$q->where('campaign_id', $campaign_id);
}])->get();
Is this documented anywhere?
Solution 2
TRY With This
$mainQuery=StockTransactionLog::with(['supplier','customer','warehouse','stockInDetails'=>function($query) use ($productId){
$query->with(['product'])->where('product_stock_in_details.product_id',$productId);
},'stockOutDetails'=>function($query) use ($productId){
$query->with(['product'])->where('product_stock_out_details.product_id',$productId);
},'stockDamage'=>function($query) use ($productId){
$query->with(['product'])->where('product_damage_details.product_id',$productId);
},'stockReturn'=>function($query) use ($productId){
$query->select('id','return_id','product_id');
$query->with(['product'])->where('product_return_details.product_id',$productId);
}]);
Solution 3
$latitude = $request->input('latitude', '44.4562319000');
$longitude = $request->input('longitude', '26.1003480000');
$radius = 1000000;
$locations = Locations::selectRaw("id, name, address, latitude, longitude, image_path, rating, city_id, created_at, active,
( 6371 * acos( cos( radians(?) ) *
cos( radians( latitude ) )
* cos( radians( longitude ) - radians(?)
) + sin( radians(?) ) *
sin( radians( latitude ) ) )
) AS distance", [$latitude, $longitude, $latitude])
->where('active', '1')
->having("distance", "<", $radius)
->orderBy("distance")
->get();
Author by
markstewie
Web, Mobile and App developer and designer living in Auckland, New Zealand
Updated on July 13, 2022Comments
-
markstewie almost 2 years
I've finally worked out how to put together a complex query to get related models.
This is what my query currently looks like...
$campaign = Campaign::find($campaign_id); $buyers = $campaign->buyers()->with('notes')->with(['emails' => function($q){ $q->where('campaign_id', '13'); }])->get();
The complex part is I'm trying to get entries from
emails
that have both a matchingbuyer_id
&campaign_id
. This query achieves exactly what I'm after in a pretty efficient way...BUT... I can't work out how to pass in parameters to the
with
closure. At the moment I've hard coded the id13
into thewhere
query in the closure but I want it to be equal to$campaign_id
passed in to the original function.How do I do this?