【问题标题】:Where do i define the juncion table in many-to-many relationship in Laravel's Eloquent?在 Laravel Eloquent 中,我在哪里定义多对多关系中的联结表?
【发布时间】:2014-04-18 05:03:15
【问题描述】:

在 eloquent 中,我看到了多对多关系: http://laravel.com/docs/eloquent

我没有使用迁移并在 phpmyadmin 中创建了两个表“用户”和一个表“角色”。 它们都有一个“id”和“name”列。现在我做了以下模型:

class User extends Eloquent {

    public function roles()
    {
        return $this->belongsToMany('Role');
    }

}



class Role extends Eloquent {

    public function users()
    {
        return $this->belongsToMany('User');
    }

}

我的第一个问题是。是否还需要在 phpmyadmin 中制作联结表? 如果是,我如何告诉 Eloquent(例如“users_roles”)是我的连接表?

【问题讨论】:

    标签: laravel phpmyadmin eloquent


    【解决方案1】:

    您必须确实拥有该表,并且您可以遵循 Laravel 约定或在对 $this->belongsTomany(); 的调用中手动指定它。这两种方式都记录在Eloquent documentation 中。约定是按字母顺序和单数表名(roles、users、role_user)。要在调用中指定它,您可以指定各种内容:return $this->belongsToMany('ForeignModel', 'pivot_table', 'local_id', 'foreign_id');

    【讨论】:

      【解决方案2】:

      是的,您仍然需要创建表。

      在您的模型中,将表名作为第二个参数添加到 belongsToMany。

      【讨论】:

        猜你喜欢
        • 2014-12-13
        • 2019-01-21
        • 2019-06-13
        • 2018-06-15
        • 2018-10-05
        • 2014-04-18
        • 2019-04-29
        • 2017-04-20
        • 2018-12-14
        相关资源
        最近更新 更多