我目前拥有一个用户到组关系(ManyToMany)和一个数据透视表group_user。我希望用户能够创建一个组,但是一旦创建了组,我该如何创建,创建者成为该组的成员?
目前我有
我的数据透视表(group_user):
Schema::create('group_user', function(Blueprint $table)
{
$table->integer('group_id')->unsigned()->index();
$table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
我的群组表(群组):
Schema::create('groups', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
});
我的用户表(用户):
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('name');
$table->string('lastname');
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
我的模型有以下内容:User.php
public function groups()
{
return $this->belongsToMany('App\Group');
}
Group.php
public function users()
{
return $this->belongsToMany('App\User');
}
我应该在控制器中编写什么创建函数,以便在用户创建组时,他自动成为该组的成员(自动建立透视关系)?
答案 0 :(得分:1)
参见attach()和detach()。
$user = User::find(1);
$user->groups()->attach(10); // pivot relationship of this user to group of id 1.
OR
$group = Group::find(10);
$user->groups()->save($group);
对于此用户的许多群组:
$user->groups()->sync(array(1, 2, 3));
答案 1 :(得分:1)
这应该有效,请确保您实施验证,等等。
public function store(Request $request)
{
$group = Group::create([ // <-- if names are unique. if not, then create is fine
'name' => $request->get('name')
]);
auth()->user()->groups()->attach([$group->id]);
return view('your.view');
}
还要确保添加:
use App\Group;