我有三个模型:Person、Feature 和 PersonFeature。 PersonFeature 是一个具有两个外键的联结表,person_id 引用 person 表中的 id,feature_id 引用 feature 表中的 id。
我的问题是 Yii2 中的 Gii 是否生成所有相关关系。这些是三个模型中每一个的关系
人:
public function getPersonfeatures()
{
return $this->hasMany(Personfeature::className(), ['personid' => 'id']);
}
特点:
public function getPersonfeatures()
{
return $this->hasMany(Personfeature::className(), ['featureid' => 'id']);
}
人物特征:
public function getPerson()
{
return $this->hasOne(Person::className(), ['id' => 'personid']);
}
public function getFeature()
{
return $this->hasOne(Feature::className(), ['id' => 'featureid']);
}
但是当我浏览其他帖子时,我看到存在一个“viaTable”操作,例如:
public function getPerson() {
return $this->hasMany(Person::className(), ['id' => 'personid'])
->viaTable('personfeature', ['featureid' => 'id']);}
所以基本上我的问题是,Yii 应该为我生成这个吗?或者我可以手动添加吗?
干杯
最佳答案
最后一个函数(使用 viaTable)是多对多关系,该函数可以像任何其他关系函数一样使用(例如在 ->with()
查询中)。
您的连接表不需要模型,除非您想将其用于其他用途。
希望这对您有所帮助。
关于php - Yii2 中的 Gii CRUD 生成连接表关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29960822/