Activequery And Default Scope

Hello:

Does anyone know if there is a way to have a default scope AND an ActiveQuery for an ActiveRecord. Or maybe I’m looking at this the wrong way for Yii2.

I have a project where all of the data is keyed off of the user_id. So I don’t want to have to keep adding the where "customer_id = " clause to every single query. In Yii 1.0 there was the concept of a default scope.

But how would I go about using the default scope AND and ActiveQuery class. Ex:




<?php


namespace app\models;


use yii\db\ActiveQuery;


class AuditionQuery extends ActiveQuery

{

    public function booked()

    {

        $this->andWhere('audition_id in (select audition_id from booking where customer_id = '.

			Yii::app()->request->cookies['customer_id']->value).')');

        return $this;

    }

}


?>



Any ideas would be helpful.

Thanks.

In yii2 you still have that default scope

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#default-scope

Yes but when you use an ActiveQuery you pass along the query like this:




    public static function find()

    {

        return new AuditionQuery(get_called_class());

    }



So then how would I implement a default scope here?

Thanks.

if you are extending ActiveQuery then you should be able to call where on AuditionQuery


public static function find()

{

	// like so

	$query = new AuditionQuery(get_called_class())

	return $query->andWhere(['audition_id' => 1]);

}



note: I did not test this code

Cool. Simple! Thanks so much.

np. glad could help

I’m not using Yii-2 yet, but I’m just curios.

In Yii-1, my default scope is over 200 lines of code - checking user access permissions, filtering records on security levels, etc.

Is it possible in Yii-2 to constantly incorporate such default scope in all forms of queries and database CRUD actions?

@Gerhard of course you can do all that in yii2 as well, its easy to port your 1 code 2, I used yii2 for a insurance system recently no issues at all and speed is not that bad