L
L
link_irk2015-03-05 09:14:51
Yii
link_irk, 2015-03-05 09:14:51

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:
8XowKWN.png
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;

In the Sites model, I have a getter:
public function getNews()
{
    return $this->hasMany(News::className(), ['id' => 'news_id'])->viaTable('site_news', ['site_id' => 'id']);
}

Accordingly, I can get news related specifically to this site anywhere by contacting $news = Yii::$app -> params['site'] -> newsand receiving a collection of News objects
. But what if I need to extract not all the news, but for example only 2, or select the news that satisfies some condition?
And is such an organization of models generally correct?
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vit, 2015-03-05
@link_irk

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 question

Ask a Question

731 491 924 answers to any question