0

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Max Zhuravlev
  • 324
  • 3
  • 13

1 Answers1

0

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.

Mihai P.
  • 9,307
  • 3
  • 38
  • 49
  • you have two relations here, but in my case we need only one unified relation - that's where the case. I need to have one place from which i can get parent pair, weather I'm first item or second, $item->relatedParentPair should return my pair – Max Zhuravlev Mar 04 '14 at 06:35
  • The closest i got is with 'any' => array(self::HAS_MANY, 'Order', array('BillingAddress_id', 'ShippingAddress_id')), but that uses AND it does not use OR. You can create a getter, something like function getrelatedParentPair() {return Order::model()->find(condition)}, that will act like a relation under some circumstances (meaning you can use foreach($model->relatedParentPair...), but it will not work if you use some advance extensions like SaveWithRelated. – Mihai P. Mar 04 '14 at 09:15