Max Zhuravlev
Max Zhuravlev

Reputation: 334

Yii how to set HAS_ONE relation where pk in one of two columns of related model?

I have a PairModel

pair_id | first_item_id | second_item_id |

And Item model

item_id | some_common_item_fields

Relations of pair looks like that:

public function relations()
{
   return array(
       'relatedFirstItem' => array(self::BELONGS_TO, 'Cash', 'debit_cash_id'),
       'relatedSecondItem' => array(self::BELONGS_TO, 'Cash', 'credit_cash_id'),
   );
}

But how to set relation from Item to ites pair?

public function relations()
{
   return array(
       'relatedPair' => array(self::HAS_ONE, 'PairModel', '???'),
   );
}

Getter is not solution (because I need to use relatedPair in scopes etc)

I think relation should look like this:

public function relations()
{
   return array(
       'relatedPair' => array(self::HAS_ONE, 'PairModel', '', 'on'=>'(first_item_id=:itemPkAlias or second_item_id=:itemPkAlias)'),
   );
}

But it looks like itemPkAlias is given dinamically and I can't set or get it in advance.

Upvotes: 0

Views: 722

Answers (1)

Mihai P.
Mihai P.

Reputation: 9367

In 1 model I have

return array_merge(
    array(
            'billingAddress' => array(self::BELONGS_TO, 'Address', 'BillingAddress_id'),
            'shippingAddress' => array(self::BELONGS_TO, 'Address', 'ShippingAddress_id'),
        ),
    parent::relations()
);      

In the other model I have

/**
 * @return array relational rules.
 */
public function relations()
{

    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array_merge(
        array(
            'orders_billing' => array(self::HAS_MANY, 'Order', 'BillingAddress_id'),
            'orders_shipping' => array(self::HAS_MANY, 'Order', 'ShippingAddress_id'),
            ),
        parent::relations()
    );      
}

Just normal Yii declaration.

Upvotes: 0

Related Questions