Laravel Eloquent:带有查询参数

时间:2014-11-11 02:42:11

标签: laravel laravel-4 eloquent

我终于找到了如何整理复杂查询以获取相关模型的方法。

这是我目前的查询...

    $campaign = Campaign::find($campaign_id);
    $buyers = $campaign->buyers()->with('notes')->with(['emails' => function($q){
        $q->where('campaign_id', '13');
    }])->get();

复杂的部分是我试图从emails获得具有匹配buyer_id&的条目。 campaign_id。这个查询以一种非常有效的方式实现了我所追求的......

但是......我无法解决如何将参数传递给with闭包的问题。目前,我已将ID 13硬编码到闭包中的where查询中,但我希望它等于传递给原始函数的$campaign_id

我该怎么做?

4 个答案:

答案 0 :(得分:14)

如果有人遇到同样的问题,请将其解决...需要使用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();

这是否记录在任何地方?

答案 1 :(得分:2)

尝试使用此

$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);
        }]);

答案 2 :(得分:0)

$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();

答案 3 :(得分:0)

$fpr = FPR::with([
  'detail','of_permintaan.detail', 
  'of_permintaan.detail.pembelian'=>function($q)use($id){
       return $q->where('pembelian_id',$id);}
])->findOrFail($id);

好吧,以防万一您需要通过它的 child-child 关系,但是我不建议这样做