我試圖在網格視圖中執行搜索,如解釋here。當你有一個關聯到特定表的單個字段時,這種技術可以正常工作。但是,我有一個表包含與另一個表(資源)有關係的兩個字段(resource_to_id,resource_from_id)。yii2搜索鏈接到同一個表的兩個字段
在下面的模型代碼中,我可以使用$ query-> joinwith行來搜索該字段,但不能同時使用兩者。我如何實現搜索這兩個資源字段?
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Messages;
/**
* MessagesSearch represents the model behind the search form about `app\models\Messages`.
*/
class MessagesSearch extends Messages
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'message_read'], 'integer'],
[['subject', 'message', 'time_sent', 'resource_to_id', 'resource_from_id'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Messages::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->joinwith('resourceFrom');
//$query->joinwith('resourceTo');
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'time_sent' => $this->time_sent,
'message_read' => $this->message_read,
]);
$query->andFilterWhere(['like', 'subject', $this->subject])
->andFilterWhere(['like', 'message', $this->message])
->andFilterWhere(['like', 'resources.resource_name', $this->resource_to_id])
->andFilterWhere(['like', 'resources.resource_name', $this->resource_from_id])
;
return $dataProvider;
}
}
我覺得..你必須使用加入,並把條件with'resources.resource_name = resource_to_id OR resources.resource_name = resource_from_id' –
@Arshad Shaikh你如何使用yii2創建這樣的條件? – fullerm
試試這個。 '$ query-> andWhere('resources.resource_name = resource_to_id OR resources.resource_name = resource_from_id');' –