G
G
Ghost26922018-10-09 13:44:08
Yii
Ghost2692, 2018-10-09 13:44:08

How to search by related model in Yii2?

$query = ReportMailing::find()->where(['user_id' => Yii::$app->user->id]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => Yii::$app->params['showEntriesDefault'],
                'forcePageParam' => false,
                'pageSizeParam' => false,
            ],
            'sort' => [
                'defaultOrder' => [
                    'created' => SORT_DESC,
                ]
            ],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            return $dataProvider;
        }

        $query->andFilterWhere(['like', 'mailing_id', $this->subject]);

        return $dataProvider;

And the ReportMailing communication model
public function getMailing()
    {
        return $this->hasOne(Mailing::className(), ['id' => 'mailing_id']);
    }

I need to find data in another table by subject field. How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-10-09
@Ghost2692

Change your search model code a bit.
More or less like this:

$query = ReportMailing::find()->joinWith('mailing')->where(['user_id' => Yii::$app->user->id]);
  
   // формируете $dataProvider

        $query->andFilterWhere(['like', '{{%mailing}}.subject', $this->subject]);

        return $dataProvider;

ps I think like is not needed here
$query->andFilterWhere(['{{%mailing}}.subject' => $this->subject]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question