[英]Yii2. Models related
I have 3 models: Items, Serials and SerialsCategories. 我有3个模型:Items,Serials和SerialsCategories。 When I show Item form (to create or update) I need to show the serials which belongs to a categoryId selected in a previous step. 当我显示项目表单(创建或更新)时,我需要显示属于上一步中选择的categoryId的序列。 A serial can belong to more than one category. 序列可以属于多个类别。
Right now I have on my Item model: 现在我在Item模型上有:
public function getSerialsTypeByCategory() {
return (new SerialType)->getByCategory($this->itemCategoryId);
}
On my SerialType model: 在我的SerialType模型上:
public function getByCategory($itemCategoryId) {
return SerialTypeItemCategory::find()->select(['serialTypeId'])->where(['itemCategoryId' => $itemCategoryId])->all();
}
This is working, it does what I need but ... Is this the proper way? 这是可行的,它可以满足我的需要,但是...这是正确的方法吗? is there a better way? 有没有更好的办法?
it's not wrong what you are doing. 你在做什么没错。 but there is something more - check this link: Working with Relational Data 但还有更多内容-检查此链接: 处理关系数据
if you use ->hasOne
and ->hasMany
to define relations, your model gains some extra benefits, like joining with lazy or eager loading: 如果使用->hasOne
和->hasMany
定义关系,则模型会获得一些额外的好处,例如加入懒惰或急切的装载:
Item::findOne($id)->with(['categories'])->all();
with a relation, you can also use ->link
and ->unlink
, to add/delete related data without having to think about linked fields. 对于关系,还可以使用->link
和->unlink
来添加/删除相关数据,而不必考虑链接字段。
Further, it is easy to define relations via junction table: 此外,通过联结表定义关系很容易:
class Order extends ActiveRecord
{
public function getItems()
{
return $this->hasMany(Item::className(), ['id' => 'item_id'])
->viaTable('order_item', ['order_id' => 'id']);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.