Hey folks,
I have PHP experience for several years, but I just dipped into Yii2 last week. And I regret that I haven’t done it earlier . This is so great.
My question refers to the relations in a ActiveRecord Model.
Let’s say I have two tables:
[indent]member[/indent]
id | id_department | name
[indent]department[/indent]
id | name
One member can only have one department. And a department can have multiple member.
In a classic SQL Query I just would do the following:
[sql]SELECT
m.id, m.name AS member, d.name AS department
FROM
member m
LEFT JOIN
department d ON d.id = m.id_department[/sql]
Now I want to integrate the department name in my member model.
I read the relational part of the ActiveRecord Guide and there is this hasMany() and hasOne() thing.
Perhaps i got something wrong, but when I do that I won’t get the JOIN-query I posted above.
As far as i understand I get something like that:
[sql]SELECT * FROM member;
SELECT * FROM department WHERE id IN (…)[/sql]
But that is not what I want to achieve. I would like to have that classic JOIN query since I only need the department name.
At the moment I have the following workaround:
<?php
$query = Member::find()
->from('member m')
->select([
'id' => 'm.id',
'member' => 'm.name',
'department' => 'd.name',
])
->leftJoin('department d', 'd.id = m.id_department');
?>
I feel not right with that. That is against the model architecture, isn’t it?
When the member table grows and has more fields, I have to manually add all of them in the select method.
And when there are more connected tables, I need to add the left joins as well.
I hope my situation became clear. Is there any best practice for that? I have that kind of cases very often.
Cheers,
Salbei