【发布时间】:2018-11-15 20:03:29
【问题描述】:
它们之间有 3 个模型。 示例
class A extends ActiveRecord
{
public static function tableName(){
return 'tbl_a';
}
public function getB()
{
return $this->hasOne(B::className(), ['column' => 'column']);
}
}
class B extends ActiveRecord
{
public static function tableName(){
return 'tbl_b';
}
public function getC()
{
return $this->hasOne(C::className(), ['column' => 'column']);
}
}
我有下一个代码:
$result = A::find()->joinWith('b')->where('');
if () {
A->joinWith('b.c')->where('');
}
$result->createCommand()->rawSql;
结果我有下一个 sql:
select * from tbl_a left join tbl_b on ... join tbl_b on ... join tbl_c on ... where ...
如您所见,sql 查询重复了表关系“tbl_b”。你知道为什么吗?
更新
好的,我更详细地研究了我的问题。 如果使用不同的 JOIN 类型,则表连接是重复的。 下一个原始模型:
class Myuser extends ActiveRecord
{
public static function tableName(){
return 'myuser';
}
public function getProfile()
{
return $this->hasOne(Profile::className(), ['user_id' => 'id']);
}
}
class Profile extends \yii\db\ActiveRecord {
public static function tableName(){
return 'profile';
}
public function getCity()
{
return $this->hasOne(City::className(), ['id'=>'city_id']);
}
}
执行代码:
$get_city = 1;
$u = Myuser::find()->joinWith('profile', 0, 'INNER JOIN');
if ($get_city) {
$u->joinWith('profile.city');
}
echo $u->createCommand()->rawSql;
结果:
SELECT `myuser`.* FROM `myuser`
INNER JOIN `profile` ON `myuser`.`id` = `profile`.`user_id`
LEFT JOIN `profile` ON `myuser`.`id` = `profile`.`user_id`
LEFT JOIN `city` ON `profile`.`city_id` = `city`.`id`
如果我需要获取唯一的表格“个人资料”并从表格“城市”添加字段,如何避免重复。如果 'city' 表中没有字段,则 value 应为 'null'。
【问题讨论】:
-
你能在这里展示一些真实的代码作为例子吗?这些代码 sn-ps 不是有效的 PHP 代码,所以很难理解你的问题。
-
A->joinWith('b.c')->where('');的情况似乎没有帮助 -
@rob006 我更新了我的问题。