[英]into my database `first_name` is showing as 0 and last_name is showing as “Arora” after updating name
[英]filter first_name and last_name from two relation pointing to same table
我在user
表中有列first_name
和last_name
,這又與order_item
表相關,其中instructor_id
和user_id
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`
您可以嘗試使其與此類似:
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
這比我想的要簡單得多,但花了很多時間來解決。 但我仍然不清楚為什么問題中的方法不起作用。
就像我所做的那樣,我將查詢分開如下並在查詢中使用了別名。
現存的
$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]);
它工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.