请让我从下面的示例开始:
我有3张桌子:
users(id,name,family)
roles(id,user_id,chart_id,name,code)
chart(id,name)
关系:
users-roles = 1-n
roles-users = 1-1
roles-chart = 1-1
Yii活动记录类:
class User extends ActiveRecord {
public function getRoles(){
return $this->hasMany(Role::className(),['user_id' => 'id']);
}
}
class Role extends ActiveRecord {
public function getUser(){
return $this->hasOne(User::className(),['id' => 'user_id']);
}
public function getChart(){
return $this->hasOne(Chart::className(),['id' => 'chart_id']);
}
}
所以我想要角色并使用这段代码:
$roles = Role::find()
->select('roles.id,roles.user_id,roles.chart_id,roles.name,roles.code')
->joinWith([
'user' => function($q){
$q->select('id,name,family');
},
'chart' => function($q){
$q->select('id,name');
}
])
->all();
运行此代码时,Yii创建三个查询;
首先查询:
SELECT
`roles`.`id`, `roles`.`user_id`,
`roles`.`chart_id`, `roles`.`name`,
`roles`.`code`
FROM `roles`
LEFT JOIN `users` ON `roles`.`user_id` = `users`.`id`
LEFT JOIN `chart` ON `roles`.`chart_id` = `chart`.`id`
第二次查询:
SELECT `id`, `name`, `family` FROM `users` WHERE `id` IN (1, 3)
第三个查询:
SELECT `id`, `name` FROM `chart` WHERE `id`=1
这是优化的吗?
为什么我可以在第一次查询中实现结果!
为什么Yii没有结合三个查询?像下面的代码:
SELECT
`roles`.`id`, `roles`.`user_id`,
`roles`.`chart_id`, `roles`.`name`,
`roles`.`code`,
`chart`.`id`,`users`.`id`,`users`.`name`,`users`.`family`
FROM `roles`
LEFT JOIN `users` ON `roles`.`user_id` = `users`.`id`
LEFT JOIN `chart` ON `roles`.`chart_id` = `chart`.`id`