[英]Yii2: create relation via table how to?
I can get the results using this query in mysql. 我可以在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
. 现在我有一个模型OTNote
, InstrumentMaster
和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相关的列instrument_master.instrument_name列?
ot_instrument_entry
is the linking table. ot_instrument_entry
是链接表。 In class OTNote
you should have: 在OTNote
你应该:
// 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: 在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.