Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - WHERE IN with active record

Tags:

yii2

Is it possible to make WHERE IN condition with active record? I am going through documentation, but I can't find this case. I need to perform this query and return count value.

This is the method I am using for now:

public function static findProductsOnSale($ids)
    {
        return $this->find()->where(['product_id' => $ids])->count();
    }
like image 465
Sasha Avatar asked Jul 07 '15 14:07

Sasha


People also ask

Where Active Record yii?

ActiveRecord is the base class for classes representing relational data in terms of objects. Active Record implements the Active Record design pattern. The premise behind Active Record is that an individual yii\db\ActiveRecord object is associated with a specific row in a database table.

What is Active Record in Ruby?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

Is null in Yii2 query?

Yii2 will use "IS NULL" if the $values === null , but in case the value is supplied as an array, and one of those array elements is null, it will not get any special treatment, resulting in the query never matching any records with NULL value.


1 Answers

As documentation about where() says:

['id' => [1, 2, 3], 'status' => 2] generates (id IN (1, 2, 3)) AND (status = 2)

so your method should be correct. If you want to use IN then your code should look like this:

public function static findProductsOnSale($ids)
{
    return $this->find()->where(['in', 'product_id', $ids])->count();
}
like image 106
Tony Avatar answered Oct 04 '22 12:10

Tony