大家好我想在视图文件中使用$ searchModel搜索数据,并且在显示和搜索相关表时遇到问题。
以下是我的clubname
,其中organiser
是来自Event
表格的相关数据,我正在尝试以public function rules()
{
return [
[['title', 'description', 'location', 'clubname'], 'safe'],
];
}
public function search($params)
{
$query = Event::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
$query->joinWith(['organiser']);
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->andFilterWhere([
'id' => $this->id,
'interest_id' => $this->interest_id,
]);
$query->andFilterWhere(['like', 'title', $this->title])
->andFilterWhere(['like', 'description', $this->description])
->andFilterWhere(['like', 'location', $this->location]);
$query->andFilterWhere(['like', 'organiser.clubname', $this->organiser_id]);
return $dataProvider;
}
形式进行搜索。
$search
这是我的<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<div class="row">
<?= $form->field($searchModel, 'title',[
'template' => ' <div class="col-lg-2 col-md-2 col-sm-2 col-xs-3">{label}</div><div class="col-lg-4 col-md-4 col-sm-6 col-xs-8">{input}</div>'
])->textInput(['maxlength' => true]) ?>
<?= $form->field($searchModel, 'clubname',[
'template' => ' <div class="col-lg-2 col-md-2 col-sm-2 col-xs-3">{label}</div><div class="col-lg-4 col-md-4 col-sm-6 col-xs-8">{input}</div>'
])->textInput(['maxlength' => true]) ?>
</div>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary btn-xs']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default btn-xs']) ?>
</div>
<?php ActiveForm::end(); ?>
页面及其下方的列表
title
搜索clubname
时没有问题,但我希望用户也可以使用Organiser
搜索id
表中的字段,并且它们与{{1}有关系}。
答案 0 :(得分:2)
您需要在RelationName.property
中添加searchModel
:
public function rules()
{
return [
[['title', 'description', 'location', 'organiser.clubname'], 'safe'],
];
}
然后添加attributes()
功能:
public function attributes()
{
return array_merge(parent::attributes(),
[
'organiser.clubname',
]
);
}
最后将查询添加到搜索数据中:
$query->andWhere(['Attribute_name' => $params['attribute']]);