简体   繁体   中英

Yii2: create relation via table how to?

I can get the results using this query in mysql.

SELECT    group_concat(im.instrument_name) AS instrument 
FROM      ot_note otn 
LEFT JOIN ot_instrument_entry oie ON otn.id=oie.ot_note_id
LEFT JOIN instrument_master im    ON oie.instrument_name=im.id
GROUP BY  otn.id

Now I have a model OTNote , InstrumentMaster and OTInstrumentEntry .

I have tried to use a relation using via table, but it looks like I am missing something.

I have tried to create the relation like this, but it is throwing error;

public function getInstrumentMaster()
{
    return $this
       ->hasMany(OtInstrumentEntry::className(), ['ot_note_id' => 'id'])
       ->viaTable('instrument_master', ['id'=>'instrument_name']);
}

How can I can create a relation so I can access the column instrument_master.instrument_name column which is related to ot_instrument_entry?

ot_instrument_entry is the linking table. In class OTNote you should have:

// class OTNote

public function getInstrumentMaster()
{
    return $this
       ->hasMany(InstrumentMaster::className(), ['id' => 'instrument_name'])
       ->viaTable('ot_instrument_entry', ['ot_note_id' => 'id']);
}

In class InstrumentMaster you may want to have this for vice versa access:

// class InstrumentMaster

public function getOTNotes()
{
    return $this
       ->hasMany(OTNote::className(), ['id' => 'ot_note_id'])
       ->viaTable('ot_instrument_entry', ['instrument_name' => 'id']);
}

Details can be found here .

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