Yii Framework Forum: Pass Parameter To Relations Scope - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Pass Parameter To Relations Scope Rate Topic: -----

#1 User is offline   Praxus 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 15
  • Joined: 28-August 11

Posted 07 April 2014 - 10:32 AM

Hi,

I'm wondering, is it possible to pass a parameter(variable) to a scope used in relation.

Example:


// relation in Product model
public function relations()
{
    return array(        
        'reg' => array(self::HAS_ONE, 'ProductRegional', 'product_id', 'scopes' => 'lang'),       
    );
}

// scope in ProductRegional
public function lang($langId = 1)
{
    $this->getDbCriteria()->mergeWith(array(
        'alias' => 'pr',
        'condition'=>'pr.lang_id = :langId',
        'params'=>array(':langId' => $langId),
    ));
    return $this;
}


// instantiate product
$product = Product::model()->findByPk(123);
$regionalData = $product->reg; // returns ProductRegional where lang_id=1
$regionalData = $product->reg(1); // doesn't even go in the scope, returns null

0

#2 User is offline   Keith 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,598
  • Joined: 04-March 10
  • Location:UK

Posted 07 April 2014 - 01:13 PM

Yes, click here (and scroll up a bit) to see how the parameters are applied.
0

#3 User is offline   Praxus 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 15
  • Joined: 28-August 11

Posted 08 April 2014 - 02:55 AM

View PostKeith, on 07 April 2014 - 01:13 PM, said:

Yes, click here (and scroll up a bit) to see how the parameters are applied.


I presume you mean this:
$users=User::model()->findAll(array(
    'with'=>array(
        'posts'=>array(
            'scopes'=>array(
                'rated'=>5,
            ),
        ),
    ),
));

My scope in ProductRegional is set up like in the example but the problem is how to call it .
I'd like to avoid writing all that 'with'=>array().. on every query and perhaps use lazy loading.
I tried it like this:
'reg' => array(self::HAS_ONE, 'ProductRegional', 'product_id', 'scopes' => array(
    'lang' => array(
        'params' => 1
    )
)),


and it works but I'd like to pass lang_id as parameter in relation and cannot figure out how.
$regionalData = $product->reg(1); //does not work

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users