简体   繁体   中英

Yii relation for composite key as foreign key and get sum

I have three tables (Booking,Ticket,Trainee_grant) with below structure

    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`)   ;

I have relation for Ticket_tb and trainee_grant_tb as below.

Ticket model

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'),
        );
    }

and TraineeGrant model as below

    public function relations() {
         return array(
           'bookingSeq' => array(self::BELONGS_TO,'Ticket','booking_id,seq'),
       );
     }

How can i add relation in Booking so that i can get SUM(amount) of all booking_id from trainee_grant table ?

I tried with below but gives me error.

Booking Model

$relations['amountTraineeGrant'] = [
                    self::STAT,
                    'TraineeGrant',
                    'booking_id',
                    'select' => 'SUM(amount)',
                ];

it gives me error as below

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".  

Am i missing something ..i am not able to find error .Plz help me

I guess you are applying relationshiop rule in wrong model. It should be applied to model Trainee_grant. Refer to this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM