【问题标题】:Pivot table for single table in LaravelLaravel 中单表的数据透视表
【发布时间】:2019-09-30 02:07:21
【问题描述】:

我正在尝试在我的网站中添加多级类别。其中一个类别可以有多个子项,也可以有多个父项。它看起来像 Laravel 中的多对多关系,我必须使用数据透视表。

所以我创建了一个名为 categories 的表和一个如下所示的数据透视表 categories_reltionship。现在我的问题是如何在 Laravel 中与这个单表建立多对多关系。

categories table
==================
id    title
===   ======
1     title_1
2     title_2
3     title_3
4     title_4
5     title_5
categories_relationship table
==================
parent_id    child_id
==========   ======
1            2
1            3
4            2
4            3
5            2
5            3

【问题讨论】:

标签: mysql laravel pivot-table


【解决方案1】:

您可以在Category 模型上使用如下方法:

//This will get you the list of categories
public function categories()
{
    return ($this->hasManyThrough('App\Models\Category', 'App\Models\CategoryRelation', 'child_id', 'id', 'id', 'parent_id'));
}

//This will get you the list of children
public function childs()
{
    return ($this->hasManyThrough('App\Models\Category', 'App\Models\CategoryRelation', 'parent_id', 'id', 'id', 'child_id'));
}

CategoryRelation 型号:

class CategoryRelation extends Model
{
    protected $table = 'categories_relationship';
}

希望能帮助你解决问题

注意:我建议你为many to many关系准备3个表,

【讨论】:

    【解决方案2】:

    在多对多关系中你应该有三个表。我希望对你下面的例子有所帮助。 在我们提到的场景中,我们有三个表,其中包含 user 、 role 和 pivot 名称,每个用户可以有多个角色,每个角色独立于多个用户。

    用户表有 my_user_id(可选名称)和其他需要列。 角色表具有 my_role_id(可选名称)和其他。 数据透视表包括 my_user_id 、 my_role_id。

    在用户模型中,您的代码应如下所示:

    class User extends Model
    {
        public function roles()
          {
             return $this->belongsToMany('App\Role', 'pivot', 'my_user_id', 'my_role_id');
          }
    }
    

    在角色模型中,您的代码应如下所示:

    class Role extends Model
    {
        public function users()
          {
             return $this->belongsToMany('App\User', 'pivot', 'my_role_id', 'my_user_id');
          }
    }
    

    也可以参考laravel官方文档: many to many relationships

    【讨论】:

      猜你喜欢
      • 2018-04-10
      • 1970-01-01
      • 2017-12-15
      • 2021-08-17
      • 1970-01-01
      • 2015-02-14
      • 2015-09-10
      • 2014-08-24
      • 2019-07-09
      相关资源
      最近更新 更多