Yii CActiveRecord relation on the foreign key of the relation

1.8k views Asked by At

This is my database structure:

CREATE TABLE `rs_payment` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `amount` int(11) NOT NULL DEFAULT '0',
  `user_fid` int(11) NOT NULL,
  `payment_created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `payment_end_date` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `user_fid` (`user_fid`),
  CONSTRAINT `rs_payment_ibfk_1` FOREIGN KEY (`user_fid`) REFERENCES `rs_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `rs_payment_to_complex` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `payment_fid` int(11) NOT NULL,
  `complex_fid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `payment_fid` (`payment_fid`),
  KEY `complex_fid` (`complex_fid`),
  CONSTRAINT `rs_payment_to_complex_ibfk_2` FOREIGN KEY (`complex_fid`) REFERENCES `rs_complex` (`id`),
  CONSTRAINT `rs_payment_to_complex_ibfk_1` FOREIGN KEY (`payment_fid`) REFERENCES `rs_payment` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `rs_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(258) NOT NULL,
  `password` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `rs_complex` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `reservation_schedule` tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

And these are my relations in PaymentToComplex model:

public function relations()
{
    return array(
        'complexF' => array(self::BELONGS_TO, 'Complex', 'complex_fid'),
        'paymentF' => array(self::BELONGS_TO, 'Payment', 'payment_fid'),
        'userF' => array(self::BELONGS_TO, 'User', 'payment_fid'),
        //'userF' => array(self::BELONGS_TO, 'User', 'paymentF.user_fid'),
    );
}

Complex and payment relations work's well. User relation is actually joined to the query like this: LEFT OUTER JOIN rs_user userF ON (t.payment_fid=userF.id).

I need to update foreign key of the userF to join on user_fid column of the rs_payment table. Commented code doesn't work.

Thanks for your help.

1

There are 1 answers

1
topher On

You should use CActiveRecord::through to get userF using paymentF as follows:

'userF' => array(self::BELONGS_TO, 'User', array('user_fid'=>'id'),'through'=>'paymentF'),

More at http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through