Laravel Eloquent:带查询参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26856581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent : with query parameters
提问by markstewie
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 matching buyer_id
& campaign_id
. This query achieves exactly what I'm after in a pretty efficient way...
复杂的部分是我试图从中获取emails
具有匹配buyer_id
& 的条目campaign_id
。这个查询以一种非常有效的方式实现了我所追求的......
BUT... I can't work out how to pass in parameters to the with
closure. At the moment I've hard coded the id 13
into the where
query in the closure but I want it to be equal to $campaign_id
passed in to the original function.
但是...我不知道如何将参数传递给with
闭包。目前,我已将 id 硬编码13
到where
闭包中的查询中,但我希望它等于$campaign_id
传递给原始函数。
How do I do this?
我该怎么做呢?
回答by markstewie
Worked it out if anyone has same problem... need to use use
statement
如果有人有同样的问题,请解决它......需要使用use
语句
$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?
这在任何地方都有记录吗?
回答by Jasim Juwel
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);
}]);
回答by Jaymin
$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();