yii2中如何从相关的table中搜索数据

How to search data from related table in yii2

大家好,我正在尝试在视图文件中使用 $searchModel 搜索数据,但在显示和搜索相关内容时遇到问题 table。

这是我的 SearchModel,其中 clubname 是来自 organiser table 的相关数据,我正在尝试以 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 table 中的字段,他们有与 id.

的关系

您需要在searchModel中添加RelationName.property:

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']]);