M
M
My joy2018-03-20 13:00:53
Yii
My joy, 2018-03-20 13:00:53

How to pull related records with a condition?

It's me again :)
There is a table with orders (orders) and a table with order logs (orders_log)
in the logs there are fields action (event name) order_id (on which order it worked) and date (when)
i.e. for one order there can be several events in chronological order (arrived, issued, sent, received).
in the search model, it pulls the first available status. but you need to pull one with the maximum date (well, that is, the most current status). how can this be checked? to keep the filter working.
$query->joinWith(['logs'])->with('logs');

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2018-03-20
@slo_nik

Good afternoon.
Try like this

->joinWith([
     'logs' => function(ActiveQuery $query){
           $query->where(/* тут условие */);
     }
 ])

A
Antarit, 2018-03-20
@Antarit

If you get your orders_log in the model, by a method that implies a relation, like

public function getLogs()
{
    return $this->hasMany(Log::className(), ['order_id' => 'id']);
}

Then in the search method of the search model, you can do this
$query->joinWith(['logs'])
//фильтры
//$query->filterWhere(какой-то фильтр)
//...
//после всех фильтров
$query->orderBy([Log::tablename().'.date'=>SORT_DESC])->limit(1);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question