R
R
Ravenenok2015-05-29 13:11:09
Yii
Ravenenok, 2015-05-29 13:11:09

Yii2 AR Join + Where, how?

There are two tables Employee and Schedule, schedule is related to employee through schedule.employee = employee.id
We need to select all employee schedules for a specific day.
In SQL the query looks like this:

select * from employee
left join schedule on schedule.employee  = employee.id
where schedule.date = <ДАТА>

In Yii, I have created models through gii, respectively, and connections.
In the controller I have the following
$qEmployee = Employee::find()->joinWith('schedules')->where(['schedule.date'=>$curDate]);
$Employee = $qEmployee->all();

The problem is that as a result, each $Employee->schdeules contains all entries from the schedule without taking into account the day, it seems that where does not work.
Where did I go wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vyachin, 2015-06-08
@vyachin

read here https://github.com/yiisoft/yii2/blob/master/docs/g... , it's a pity there is no translation yet, can you do it for me?
$qEmployee = Employee::find()->joinWith('schedules')->where(['schedule.date'=>$curDate]);
here you choose all employees!!!!! which have an entry in the schedule table for the date $curDate. Those. you made a filter on a selection from the employee table. And when you access employee->schedule everything is displayed!!! records from the schedule table for this employee.
In order to do what you want, you need to impose conditions on a selection from the schedule table. I will just give an example

$employers = Employee::find()->joinWith(['schedules'=>function ($query) use($curDate) { 
$query->where(['date'=>$curDate]);
}])->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question