H
H
hollanditkzn2017-03-14 19:03:39
Yii
hollanditkzn, 2017-03-14 19:03:39

How to write and where is left join?

I need to make sure that in yii2 the id is not displayed, but the name of the employee. sql code i know what it looks like

SELECT * FROM `zakaz` LEFT JOIN otdel ON zakaz.id_sotrud=otdel.id

But when it came to writing it in yii, the question arose of how to implement it. Found an example in the documentation
$customers = Customer::find()
    ->select('customer.*')
    ->leftJoin('order', '`order`.`customer_id` = `customer`.`id`')
    ->where(['order.status' => Order::STATUS_ACTIVE])
    ->with('orders')
    ->all();

But question 1, as I understand it, should it be inserted into ZakazQuery extends ActiveQuery
AND directly into the first function?
And yes, I also use CRUD where you need to display all the information.
Yes, and another question, will it filter and sort according to the value it received?
leaving the example tried to do
class ZakazQuery extends \yii\db\ActiveQuery
{
    $zakaz = Zakaz::find()
    ->select('zakaz.*')
    ->leftJoin('otdel', '`zakaz`.`id_sotrud` = `otdel`.`id`')
    ->all();

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2017-03-14
@slo_nik

Good evening.
Is all employee data in one table stored or in different ones?
If in different, then you can do without left join, use links between tables instead.
More details here (working with connected data)

A
Alexey, 2017-03-14
@masterfreelance

class Zakaz extends ActiveRecord
{
    public function getOtdel()
    {
        return $this->hasOne(Otdel::className(), ['id_sotrud' => 'id']);
    }
}

this way you will get the relationship between the order and department tables. That is, you can get an employee's department for each order.
If you need for a department to get all the orders of department employees, then:
class Otdel extends ActiveRecord
{
    public function getOrders()
    {
        return $this->hasMany(Zakaz::className(), ['id' => 'id_sotrud']);
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question