Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent : with query parameters

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...

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.

How do I do this?

like image 347
markstewie Avatar asked Nov 11 '14 02:11

markstewie


3 Answers

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?

like image 187
markstewie Avatar answered Oct 17 '22 16:10

markstewie


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);
        }]);
like image 23
Jasim Juwel Avatar answered Oct 17 '22 18:10

Jasim Juwel


$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();
like image 1
JayminLimbachiya Avatar answered Oct 17 '22 18:10

JayminLimbachiya