mysql - how to get last entry in given date range from pivot table -
ok, i'm stuck , need pls.
this setup:
1) table items: id, name
2) table statuses: id, title
3) table item_status: id, item_id, status_id, created_at
item model has relation:
public function statuses(){ return $this->belongstomany('status')->withtimestamps(); }
now, want items latest statuses '7' or '9', created between 2015-10-19 , 2015-10-20 closest got is:
$items = item::with('statuses')->wherehas('statuses', function ($q) { $q->where('created_at','>=','2015-10-19'); $q->where('created_at','<','2015-10-20'); $q->wherein('status_id',array('7','9')); } );
problem not working right. it gives items got 1 of these status_id's in date range. if item got status '7' on 2015-10-19, , example status '11' on 2015-10-22, in result. have only items latest (newest) status '7' or '9' in date range.
update: example: table item_status
item_id status_id created_at 1 1 2015-10-06 1 3 2015-10-07 2 6 2015-10-07 2 3 2015-10-08 2 5 2015-10-09
if set filter as: status_id = 3 , date range 2015-10-06 2015-10-09: want item 1, because item 2 in given period has another, newer status (5)
please help! tnx y
you need add ->withtimestamps()
function relationship when using timestamp columns
ex:
public function statuses(){ return $this->belongstomany('status')->withtimestamps(); }
Comments
Post a Comment