繁体   English   中英

Yii2:通过表创建关系如何?

[英]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

现在我有一个模型OTNoteInstrumentMasterOTInstrumentEntry

我试图使用通过表的关系,但看起来我错过了一些东西。

我试图创建这样的关系,但它抛出错误;

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.

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