我试图在网格视图中执行搜索,如解释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');' –