Console applications and the user component

We have this code:

'stockStatus' => array(self::HAS_ONE, 'StockStatus', 'productId', 'on' => 'storeId = :storeId', 'params' => array(':storeId' => Yii::app()->user->getState('storeId', Store::DEFAULT_ID))),

in a model named Book which I would like to access with a console command, but since the model is trying to get the user component, "unrelated" code fails to execute as well. The purpose of this is that a logged in user (which belongs to a specific store) should get specific stock information for that store which he/she is related to.

What thoughts do you guys have on this one? The only solution I’ve made so far is to make a condition like: “if isset(Yii::app()->user)” and include the relation depending on that, but it doesn’t feel so YII.

Best regards

Rikard Hassel

you can also provide scope with parameters to StockStatus like this:

public function inStore( $idstore = null ) {

   //here apply some logic what to do if no idstore is given:

   if( $idstore === null && Yii::app()->hasComponent('user') ) {

      $idstore = Yii::app()->user->getState( 'store' );

   } elseif( $idstore === null ) {

      $idstore = 'some default value';


   $this->getDdCriteria()->mergeWith( array( 'condition'=>'storeId = :storeId', 'params' => array(':storeId'=>$idstore) ) );

   return $this;


then… you can apply this scope in relation: ‘scopes’=>array( ‘inStore’ ). (you don’t need ‘on’ and ‘params’)

you can also fetch stock sizes for specific store:

$statusInStoreX = StockStatus::model()->inStore( 10 )->with( ‘product’ )->findAll();

…however I agree it is still not-so-pretty solution… and maybe conditionally returning this relation would be even better…

It’s a good idéa and probably more accurate to use a scope since that would be visible together with the condition, but in our current situation it’s not needed that much since we always work with one store at a time, so its more like a default scope.