我有三个表(Booking、Ticket、Trainee_grant),其结构如下
Booking
id (primary key)
name
Ticket
booking_id int,
seq int,
name
address,
primary key (booking_id,seq)
CONSTRAINT `fk_booking` FOREIGN KEY booking_id reference Booking
Trinee_Grant
id int
booking_id
seq
amount
CONSTRAINT `fk_trainne_ticket_grant` FOREIGN KEY (`booking_id`, `seq`) REFERENCES `ticket` (`booking_id`, `seq`) ;
我对 Ticket_tb 和 trainee_grant_tb 的关系如下。
门票模型
public function relations() {
return array(
'booking' => array(self::BELONGS_TO, 'Booking', 'booking_id'),
'traineeGrants' => array(self::HAS_MANY, 'TraineeGrant', 'booking_id'),
'traineeGrants1' => array(self::HAS_MANY, 'TraineeGrant', 'seq'),
);
}
和TraineeGrant模型如下
public function relations() {
return array(
'bookingSeq' => array(self::BELONGS_TO,'Ticket','booking_id,seq'),
);
}
如何在 Booking 中添加关系,以便可以从 trainee_grant 表中获取所有 booking_id 的 SUM(金额)?
我尝试了下面的方法,但出现了错误。
预订模式
$relations['amountTraineeGrant'] = [
self::STAT,
'TraineeGrant',
'booking_id',
'select' => 'SUM(amount)',
];
它给了我如下错误
The relation "amountTraineeGrant" in active record class "Booking" is specified with a foreign key "booking_id" that does not point to the parent table "booking".
我是否遗漏了一些东西..我无法找到错误。请帮助我
最佳答案
我猜您正在错误的模型中应用关系规则。它应该应用于模型Trainee_grant。 引用this
关于mysql - 组合键作为外键的 Yii 关系并获取总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38090228/