我在first_name
表中具有last_name
和user
列,这些列又与order_item
和instructor_id
都链接到user_id
表的user
表有关。
现在我正在OrderItem
模型中定义关系,例如:
public function getInstructor() {
return $this->hasOne(User::className(), ['id' => 'instructor_id']);
}
和
public function getCustomerName() {
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
并且在OrderSearch
模型中
public $instructor;
public $name;
$query->joinWith(['instructor','location1','customerName n']);
$query->andFilterWhere(['like', 'concat(user.first_name," ",user.last_name)', $this->name])
->$query->andFilterWhere(['like', 'concat(user.first_name," ",user.last_name)', $this->instructor]);
现在我出现类似错误
Method yii\db\ActiveQuery::__toString() must not throw an exception,
caught Exception: Serialization of 'Closure' is not allowed
如果我要在joinwith中删除别名n,则会出现类似以下错误:语法错误或访问冲突:1066不是唯一的表/别名:'user'
The SQL being executed was: SELECT COUNT(*) FROM `order_item` LEFT JOIN `user` ON
`order_item`.`instructor_id` = `user`.`id` LEFT JOIN `location` ON `order_item`.`location_id` =
`location`.`id` LEFT JOIN `user` ON `order_item`.`user_id` = `user`.`id`
这是一个有效的查询...,尽管我仍然不太了解它要实现的目标...
SELECT COUNT(*)
FROM order_item i
LEFT
JOIN user u1
ON u1.id = i.instructor_id
LEFT
JOIN location l
ON l.id = i.location_id
LEFT
JOIN user u2
ON u2.id = i.user_id
您可以尝试使其与此相似:
class Order {
...
//first relation with table COMPANY
public function getCustomer()
{
return $this->hasOne( Company::className(), ['id' => 'customerid'] ) //table COMPANY
->andOnCondition( [ '==relationAlias==.type' => 'customer' ] );
}
//second relation with table COMPANY
public function getSupplier()
{
return $this->hasOne( Company::className(), ['id' => 'supplierid'] ) //table COMPANY
->andOnCondition( [ '==relationAlias==.type' => 'supplier' ] );
}
...
}
然后我们可以写
$orders = Order::find()
->alias( 'o' )
->innerJoinWith('customer c')
->innerJoinWith('supplier s');
建立查询
select o.* from order o
join company c on c.id = o.customerid and c.type = 'customer'
join company s on s.id = o.supplierid and s.type = 'supplier'
此问题在github上提出了解决方案:https://github.com/yiisoft/yii2/issues/10883
当时我想的要简单得多,但是花了很多时间解决。但我仍不清楚为什么问题中的方法不起作用。
[就像我所做的一样,我按如下所示分隔查询并在查询中使用别名。
existing
$query->andFilterWhere(['like', 'concat(user.first_name," ",user.last_name)', $this->name])
->$query->andFilterWhere(['like', 'concat(user.first_name," ",user.last_name)', $this->instructor]);
更新
$query->andFilterWhere(['like', 'concat(n.first_name," ",n.last_name)', $this->name]);
$query->andFilterWhere(['like', 'concat(user.first_name," ",user.last_name)', $this->instructor]);
并且运行正常。