Answer the question
In order to leave comments, you need to log in
ActiveRecord: How to select data by condition through a join table?
Hello.
I have 3 sites on Yii2, they work on the same engine, on the same database, because most of the data overlaps.
Configuration: advanced
The structure of the database is as follows:
In frontend/web/index.php I get the site model:
$site = Sites::find() -> where(['domain' => 'http://'.$_SERVER['HTTP_HOST']]) -> one();
Yii::$app -> params['site'] = $site;
public function getNews()
{
return $this->hasMany(News::className(), ['id' => 'news_id'])->viaTable('site_news', ['site_id' => 'id']);
}
$news = Yii::$app -> params['site'] -> news
and receiving a collection of News objects Answer the question
In order to leave comments, you need to log in
getNews does not actually return a list of news, but a query object, on which you can attach additional conditions before making a selection.
An example of getting two latest news:
The actual request to the database and getting the list of news happens only at the last step - when calling all().
An example of adding a condition:
$news = Yii::$app->params['site']->getNews()->andWhere(['type' =>1])->all()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question