Tôi gặp sự cố với Bảng quan hệ Yii 2. Công việc của tôi có nhiều mối quan hệ, nhưng chỉ trong trường hợp này trả lại cho tôi một lỗi:Yii 2: nhiều mối quan hệ với cùng một bảng
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'father.name' in 'where clause'
Tôi nghĩ rằng vấn đề là mối quan hệ kép với cùng một bảng "Đại lý". Xem đoạn mã trong mô hình:
public function getAgent()
{
return $this->hasOne(Agent::className(), ['id' => 'id_agent']);
}
public function getFather()
{
return $this->hasOne(Agent::className(), ['id' => 'id_father']);
}
Trong GridView của tôi Tôi thấy giá trị chính xác, nhưng khi tôi cố gắng lọc bằng ORDER hoặc bằng "vàWhere", Yii2 trả về lỗi.
Dưới đây bạn có thể tìm thấy các đoạn mã cho searchModel:
$dataProvider->sort->attributes['agentName'] = [
'asc' => ['agent.name' => SORT_ASC],
'desc' => ['agent.name' => SORT_DESC],
'default' => SORT_ASC
];
$dataProvider->sort->attributes['fatherName'] = [
//'asc' => ['father.name' => SORT_ASC],
//'desc' => ['father.name' => SORT_DESC],
'default' => SORT_ASC
];
//.......
$query->andFilterWhere(['like', 'agent.name', $this->agentName]);
$query->andFilterWhere(['like', 'father.name', $this->fatherName]);
Các AgentName thuộc tính hoạt động tốt. Bất kỳ đề xuất nào? Cảm ơn bạn!
------- UPDATE: nhiều mã --------- searchModel:
public function search($params)
{
$agent_aux = new Agent();
$agent_id= $agent_aux->getAgentIdFromUser();
if (Yii::$app->user->can('admin')){
$query = Contract::find();
}
else{
$query = Contract::find()->where(['contract.agent_id' => $agent_id]);
}
$query->joinWith(['agent','seminar']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
$dataProvider->sort->attributes['seminar_location'] = [
'asc' => ['seminar.location' => SORT_ASC],
'desc' => ['seminar.location' => SORT_DESC],
];
$dataProvider->sort->attributes['agentName'] = [
'asc' => ['agent.name' => SORT_ASC],
'desc' => ['agent.name' => SORT_DESC],
'default' => SORT_ASC
];
$dataProvider->sort->attributes['fatherName'] = [
//'asc' => ['father.name' => SORT_ASC],
//'desc' => ['father.name' => SORT_DESC],
'default' => SORT_ASC
];
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'data' => $this->data,
'id_agent' => $this->id_agent,
'id_father' => $this->id_father,
'id_seminar' => $this->id_seminar,
]);
$query->andFilterWhere(['like', 'agent.name', $this->agentName]);
$query->andFilterWhere(['like', 'father.name', $this->fatherName]);
return $dataProvider;
}
Có thể bạn đã viết sai chính tả tên cột. –
@InsaneSkulll nếu tôi sử dụng "đại lý" làm tên cột (bây giờ tôi sử dụng "cha", tên của mối quan hệ) tìm kiếm lọc dữ liệu với quan hệ đầu tiên (Agent):/ – garsim
Bạn có một dòng $ query-> với (['đại lý', 'cha']) hay bất cứ thứ gì như thế? Bạn có thể hiển thị toàn bộ nguồn truy vấn không? – robsch