Answer the question
In order to leave comments, you need to log in
How to display only the last 10 records from an activerecord link?
Hello.
I can't solve the next question. There is a model with a connection. It is necessary to display in the widget only the last 10 records from the link. I so understood that limit in communications does not work.
Example:
1. Categories of news, 5 items
2. News as a link to a category (only the last 10 news sorted by ID are needed)
2.1. Comments to the news in the form of a link to the news. Registered in the news model.
2.2. Pictures of the news in the form of a link to the news. Registered in the news model.
When displaying categories, it is necessary to display only the last 10 news from the link.
I do it like this in the model:
In the widget:
$models = Yii::$app->db->cache(function (Connection $db) {
return Categories::find()
->alias('cat')
->select('cat.id, cat.name, cat.alias, cat.status')
->with('news')
->where(['cat.id' => [1,2,3,4,5])
->andWhere('cat.status = :cat_status', ['cat_status' => 1])
->orderBy([
new Expression(sprintf("FIELD(cat.id, %s)", implode(",", [1,2,3,4,5])))
])
->all();
});
public function getNews()
{
return $this->hasMany(News::className(), ['category_id' => 'id'])
->alias('new')
->select('new.*')
->with(['comments, 'photos',])
->where('new.status != :new_status', ['new_status' => 9])
->orderBy(['new.id' => SORT_DESC])
->limit(10);
}
<?php foreach($model_category->news as $key => $item) : ?>
// Выводим новости категории и связанные данные для них
<?php endforeach; ?>
public function getNewsCategory($items = 10)
{
return $this->getNews()->limit($items)->all();
}
Answer the question
In order to leave comments, you need to log in
$sql = 'Select ........';
$model = YourModel::findBySql($sql)->all();
I think that you need to split the query like this:
1. Select category id.
2. Select news for each category, with links to comments and pictures.
And the fact that it turns out 35-55 requests is not a lot, you need to look at what they are.
See what data format is obtained when executing the query:
News::find()->where(['category_id' => $id])->with('comments')->with('photos')->asArray()->limit(10)->all()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question