我正在構(gòu)建一個(gè)小型應(yīng)用程序,以便在 Laravel 7 中試驗(yàn)多對(duì)多關(guān)系。該應(yīng)用程序與項(xiàng)目和用戶(多對(duì)多)有關(guān)。經(jīng)過(guò)身份驗(yàn)證的用戶可以創(chuàng)建新項(xiàng)目。每個(gè)項(xiàng)目都有自己的頁(yè)面。在項(xiàng)目頁(yè)面上,會(huì)呈現(xiàn)一個(gè)列表,其中包含作為該項(xiàng)目成員的每個(gè)用戶的名稱,每個(gè)名稱旁邊都有一個(gè)按鈕,用于從該項(xiàng)目中刪除特定用戶/成員?,F(xiàn)在,我陷入了“刪除用戶”功能。我不明白如何獲取列表中每個(gè)用戶的 id,并將其傳遞給將“分離”多對(duì)多關(guān)系的函數(shù)。我的文件如下:遷移:用戶表:public function up(){ Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->boolean('is_admin')->nullable(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });}項(xiàng)目表:public function up(){ Schema::create('projects', function (Blueprint $table) { //primary key $table->bigIncrements('id'); //foreign keys columns $table->unsignedBigInteger('user_id'); //normal table columns $table->string('title')->unique(); //created_at and updated_at columns $table->timestamps(); //add constraints $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); });}項(xiàng)目_用戶_表(數(shù)據(jù)透視表):public function up(){ Schema::create('project_user', function (Blueprint $table) { $table->foreignId('project_id')->constrained(); $table->foreignId('user_id')->constrained(); $table->timestamps(); });}型號(hào):用戶.php:public function projects(){ return $this->belongsToMany('App\Project');}項(xiàng)目.php:protected $fillable = ['name'];public function members(){ return $this->belongsToMany('App\User');}public function creator(){ return $this->belongsTo('App\User', 'user_id', 'id');}你們能幫忙嗎?先感謝您
1 回答

海綿寶寶撒
TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
嘗試這個(gè):
public function remove_user(Project $project, User $member)
{
? ? $project->members()->detach($member->id);
? ? return redirect('/projects/'.$project->id);
}
因?yàn)槟诼肪€中傳遞了兩個(gè)參數(shù)。因此,您將獲得一個(gè)模型實(shí)例Project和一個(gè)User模型實(shí)例。然后只需訪問關(guān)系并訪問detach()方法$user->id即可完成工作。您可以通過(guò)在方法中傳遞 ids 數(shù)組來(lái)分離多個(gè)用戶,或者通過(guò)不帶參數(shù)detach()調(diào)用來(lái)從項(xiàng)目中刪除所有用戶。detach()
- 1 回答
- 0 關(guān)注
- 125 瀏覽
添加回答
舉報(bào)
0/150
提交
取消