[英]Automaticlly attach to pivot table in Laravel 5
我目前有一个具有数据透视表group_user的用户与组的关系(ManyToMany)。 我希望用户能够创建一个组,但是一旦创建了该组,如何使创建者成为该组的成员呢?
目前我有
我的数据透视表(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');
}
我应该在控制器中编写什么创建函数,以便当用户创建组时,他自动成为该组的成员(自动建立支点关系)?
请参阅attach()和detach()。
$user = User::find(1);
$user->groups()->attach(10); // pivot relationship of this user to group of id 1.
要么
$group = Group::find(10);
$user->groups()->save($group);
对于此用户的许多组:
$user->groups()->sync(array(1, 2, 3));
这应该起作用,请确保您实施验证等。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.