lundi 12 octobre 2015

How to filter on pivot fields in laravel

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire