I have 3 tables, users , orders and statuses . Pivot table order_status has extra columns: user_id and created_at (to get which user and when set that status). Order model has method:
// get latest status for order, and tie user (user_id in pivot table)
public function latestStatus(){
return $this->belongsToMany('Status')
->select(array('*','User.name'))
->orderBy('order_status.created_at','desc')
->join('users','order_status.user_id','=','users.id')
->withTimestamps();
->limit(1,0);
}
so if i call:
$orders = Orders::with('latestStatus')->get();
i can have orders with latest status. that's ok.
i need to have some filtering, both on order properties and by latest status, for example: (table orders has columns location , buyer ) - how to pull all orders with:
order.location_id = in ("ny", "nm")
order.buyer_id = in ("1", "3")
order_status.user_id = in ("1", "5")
order_status.created_at = between (2015-10-04, 2015-10-06)
order_status.status_id = in ("2", "8", "9")
Calling "where" on Orders just solves location and buyer part...
$orders = Orders::whereIn('location_id',["ny", "nm"])
->whereIn('buyer_id',["1","3"])
->with('latestStatus')
->get();
so question is how to filter on pivot fields (find orders with specific statuses created between specific dates)?
tnx Y
Ok, here's how i did it:
$orders = Order::with('lateststatus')
->whereHas('lateststatus', function ($q) use ($dateTo, $dateFrom, $statuses) {
$q->where('order_status.created_at','>=',$dateFrom);
$q->where('order_status.created_at','<',$dateTo);
$q->whereIn('order_status.status_id',$statusi);
}
);
$orders = $orders->whereIn('location_id',$locations); }
$orders = $orders->whereIn('user_id',$users); }
$orders = $orders->->get();
PS: i altered db structure, so now i'm keeping user_id in orders table.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.