gpt4 book ai didi

MySQL/Eloquent belongsToMany 关系 - 两个表是否允许相同的数据透视表?

转载 作者:行者123 更新时间:2023-11-29 02:21:10 26 4
gpt4 key购买 nike

是否允许有两个表,每个表都具有 belongsToMany() 关系,并使用相同的数据透视表?

这是我的用户表:

enter image description here

这是我的组织表:

enter image description here

这是数据透视表:

enter image description here

这是 Eloquent User.php 模型:

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {

protected $table = 'users';
public $timestamps = true;

use Authenticatable;
use SoftDeletes;

protected $dates = ['deleted_at'];

public function orgs()
{
return $this->belongsToMany('App\Org', 'org_user', 'org_id', 'user_id')->withPivot('role_id');
}
}

这是 Eloquent Org.php 模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Org extends Model {

protected $table = 'orgs';
public $timestamps = true;

use SoftDeletes;

protected $dates = ['deleted_at'];

public function users()
{
return $this->belongsToMany('App\User', 'org_user', 'org_id, user_id')->withPivot('role_id');
}

}

这样做可以吗? (即使用共享数据透视表)有经验的人是否预见到这里的任何问题?或者也许有人可以评论标准做法/分享一些见解?

最佳答案

绝对可以!这就是多对多关系的美妙之处,实际上就是 http://laravel.com/docs/4.2/eloquent#many-to-many 的例子。 UserRole 类都设置了 belongsToMany。在这种情况下(听起来也像您的情况),认为一个用户可以拥有多个角色,并且每个角色可以与多个用户相关联。

关于您的最后两个问题,唯一让我停顿的部分是数据透视表中 role_id 的使用。您提供的代码没有详细说明其用途。只要 User 永远只有一个与 Org 相关联的角色,这很好,但如果它可能不止一个,我会推荐另一个表来保存它用户组织角色关系。

关于MySQL/Eloquent belongsToMany 关系 - 两个表是否允许相同的数据透视表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31633264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com