代码之家  ›  专栏  ›  技术社区  ›  Roman Khegay

雄辩的ORM | Laravel有许多(不止1个)关系

  •  2
  • Roman Khegay  · 技术社区  · 7 年前

    堆栈溢出!

    我是usign Laravel。问题是关于雄辩的关系。

    项可能有1个或多个类型。


    项目php:

    public function types() 
    {
        return $this->hasMany('App\Type');
    }
    

    类型php:

    public function items() 
    {
        return $this->belongsToMany('App\Item');
    }
    

    项目表:

    id
    name
    

    类型表:

    身份证件
    名称
    

    问题是

    我有四种类型。项目1有2种类型,项目2有1种类型。 我应该如何在数据库中存储项目类型?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alexey Mezenin    7 年前

    您需要定义两个 belongsToMany() 关系。在 Item 型号:

    public function types() 
    {
        return $this->belongsToMany('App\Type');
    }
    

    Type 型号:

    public function items() 
    {
        return $this->belongsToMany('App\Item');
    }
    

    此外,创建 item_type 数据透视表。

    使用此 many-to-many relationship 使用 attach() , detach() sync() 方法。