[英]Yii2: create relation via table how to?
我可以在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
現在我有一個模型OTNote
, InstrumentMaster
和OTInstrumentEntry
。
我試圖使用通過表的關系,但看起來我錯過了一些東西。
我試圖創建這樣的關系,但它拋出錯誤;
public function getInstrumentMaster()
{
return $this
->hasMany(OtInstrumentEntry::className(), ['ot_note_id' => 'id'])
->viaTable('instrument_master', ['id'=>'instrument_name']);
}
如何創建關系以便我可以訪問與ot_instrument_entry相關的列instrument_master.instrument_name列?
ot_instrument_entry
是鏈接表。 在OTNote
你應該:
// class OTNote
public function getInstrumentMaster()
{
return $this
->hasMany(InstrumentMaster::className(), ['id' => 'instrument_name'])
->viaTable('ot_instrument_entry', ['ot_note_id' => 'id']);
}
在InstrumentMaster
類中,您可能希望以相反的方式訪問它:
// class InstrumentMaster
public function getOTNotes()
{
return $this
->hasMany(OTNote::className(), ['id' => 'ot_note_id'])
->viaTable('ot_instrument_entry', ['instrument_name' => 'id']);
}
細節可以在這里找到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.