Answer the question
In order to leave comments, you need to log in
Yii2: ActiveRecord how to get NOT related data?
Please tell me how, by analogy with getting ActiveQuery for related fields, get ActiveQuery for unrelated fields. For example, you need to get all unread news.
Example
There are two models of type AR: Customer and News , and the news_read table connecting them with the fields customer_id and news_id .
When a client reads a particular news item, the models are linked via link() , which adds an entry to the news_read table .
The Customer class contains a getReadNews() method that returns an ActiveQuery that can fetch all the news items that have been read. How to implement the same thing, but for not read?
class Customer extends ActiveRecord
{
public function getReadNews()
{
return $this->hasMany(News::className(), ['id' => 'news_id'])
->viaTable('{{%news_read}}', ['customer_id' => 'id']);
}
public function getUnreadedNews()
{
// ???
}
}
Answer the question
In order to leave comments, you need to log in
That is, as I understand it, you need to select all the news that do not have an id in the news_read table for a given customer_id?
If so, then the implementation can be done as follows:
public function getUnreadedNews()
{
return News::find()->where(['not in', 'id', $this->getReadNews()->select('id')]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question