如何从yii2中的相关表中查找数据

问题描述 投票:0回答:1

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

这是我的

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
有关系。

php yii2 yii2-advanced-app yii2-basic-app
1个回答
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']]);
© www.soinside.com 2019 - 2024. All rights reserved.