Yii关系为复合键作为外键并得到总和

时间:2016-06-29 04:11:06

标签: mysql yii

我有三张表格(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'),
       );
     }

如何在预订中添加关系以便我可以从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".  

我错过了什么..我无法找到错误.Plz帮帮我

1 个答案:

答案 0 :(得分:0)

我猜你是在错误的模型中应用关系规则。它应该应用于模型Trainee_grant。 请参阅this