我有以下架构
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('userName')->default('');
$table->string('userEmail')->default('');
$table->tinyInteger('active')->default(1);
$table->timestamps();
});
Schema::create('user_groups', function(Blueprint $table)
{
$table->increments('id');
$table->string('groupName')->default('');
$table->timestamps();
});
Schema::create('users_user_groups', function(Blueprint $table)
{
$table->integer('userId')->unsigned()->index();
$table->foreign('userId')->references('id')->on('users')->onDelete('cascade');
$table->integer('groupId')->unsigned()->index();
$table->foreign('groupId')->references('id')->on('user_groups')->onDelete('cascade');
$table->timestamps();
});
基本上,用户可以是许多组的一部分,而一个组可以有许多用户。
class User extends Model
{
protected $table = 'users';
protected $guarded = [];
public function groups()
{
return $this->belongsToMany('App\Group', 'users_user_groups')->withPivot('userId', 'groupId');
}
}
class Group extends Model
{
protected $table = 'user_groups';
protected $guarded = [];
public function user()
{
return $this->belongsToMany('App\User', 'users_user_groups')->withPivot('userId', 'groupId');
}
}
我认为模特还可以。然后我在我的控制器中有一个updateUsers函数
public function updateUsers()
{
$users = Helper::returnUsersFromLdap();
DB::table('users')->update(array('active' => false));
foreach($users as $userName => $userData) {
$user = User::firstOrNew(['userName' => $userName]);
foreach ($userData as $userEmail => $userDepartment) {
$user->userEmail = $userEmail;
$user->active = true;
$userGroups = Helper::returnGroupsFromLdap($userEmail);
foreach($userGroups as $group) {
$user->groups()->sync($group);
}
}
$user->save();
}
Session::flash('flash_message', 'Users updated');
Session::flash('flash_type', 'alert-success');
return Redirect::route('users.index');
}
我基本上从Active目录中获取用户列表,循环使用,并添加my users表。对于每个用户,我调用returnGroupsFromLdap将用户电子邮件作为参数传递。对于每个用户,这将返回用户所在的组
array:3 [▼
0 => "Group1"
1 => "Group2"
2 => "Group3"
]
我的问题是如何将用户组链接到用户?所以我循环每个组,然后将其添加到我的user_groups表?但是,我在哪里填充我创建的数据透视表?
对此事的任何建议都表示赞赏。
由于
答案 0 :(得分:1)
您可以使用同步方法从用户模型更新用户组:
$user->groups()->sync([1, 2, 3]);
其中[1, 2, 3]
是包含组ID的数组。 Laravel将知道在模型中的belongsToMany()relatiotnship中指定的表中保存此关系。
但您可能必须指定列名,因为默认情况下Laravel使用另一个命名约定:
return $this->belongsToMany('App\Group', 'users_user_groups')->withPivot('userId', 'userGroupsId');
查看文档以获取更多详细信息:https://laravel.com/docs/5.2/eloquent-relationships#many-to-many
答案 1 :(得分:0)
尝试:
public function up()
{
Schema::create('users_user_groups', function(Blueprint $table)
{
$table->increments('id');
$table->integer('userId')->unsigned();
$table->integer('userGroupsId')->unsigned();
});
Schema::table('users_user_groups', function(Blueprint $table) {
$table->foreign('userId')->references('id')->on('users');
$table->foreign('userGroupsId')->references('id')->on('user_groups');
});
}