How to get this kind of associations data

Ex: we 3 tables:

  1. teacher table (id, name, sex)
  2. student table (id, firstname, lastname,sex, dob)
  3. Emergencycontact table (id, type, refer_id, name, tel, email)
    Note: if the type = 1 so the refer_id is teacher id, and type = 2 the refer_id is student id.
    How we select the right emergencycontact of teacher, student in the ‘contain’ of find() or get() methods in cakephp 3x?

Thanks for help!

In EmergencyContactTable create two relations:

$this->belongsTo('Teachers', [
     'className' => 'Teachers',
     'foreignKey' => 'refer_id',
     'conditions' => [
         'Students.type' => 1
     ]
]);

$this->belongsTo('Students', [
     'className' => 'Students',
     'foreignKey' => 'refer_id',
     'conditions' => [
         'Students.type' => 2
     ]
]);

Then to find or get use:

contain(['Students', 'Teachers'])

If the record has type 1, the data will be in property ‘teacher’, if its type 2 it will be in property ‘student’.

1 Like