user3002173
user3002173

Reputation: 135

Yii2 Model search query

How can I add where condition to my Articles model so that slug(From category model) is equal to $slug?

And this is a function that Gii generated:

public function getCategory()
{
    return $this->hasOne(Categories::className(), ['id' => 'category_id']);
}

Here's my code:

    public function specificItems($slug)
    {
    $query = Articles::find()->with('category');
    $countQuery = clone $query;
    $pages = new Pagination(['totalCount' => $countQuery->count(),'pageSize' => 12]);
    $articles = $query->offset($pages->offset)
        ->limit($pages->limit)
        ->all();
    return ['articles' => $articles,'pages' => $pages];
    }

Upvotes: 1

Views: 561

Answers (1)

Beowulfenator
Beowulfenator

Reputation: 2300

Your SQL query should contain columns from both article and category table. For that you need to use joinWith().

$result = Articles::find()
    ->joinWith('category')
    ->andWhere(['category.slug' => $slug])
    ->all();

Where 'category' is then name of your category table.

However, in your code you deviate from certain best practices. I would recommend the following:

  • Have both table name and model class in singular (Article and article). A relation can be in plural, like getCategories if an article has multiple categories.

  • Avoid functions that return result sets. Better return ActiveQuery class. If you have a query object, all you need to get the actual models is ->all(). However, you can further manipulate this object, add more conditions, change result format (->asArray()) and other useful stuff. Returning array of results does not allow that.

  • Consider extending ActiveQuery class into ArticleQuery and implementing conditions there. You'll then be able to do things like Article::find()->joinWith('category')->byCategorySlug('foo')->all().

Upvotes: 1

Related Questions