亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel - 從多對多關系獲取數據

Laravel - 從多對多關系獲取數據

PHP
溫溫醬 2023-08-06 14:51:54
我正在構建一個小型應用程序,以便在 Laravel 7 中試驗多對多關系。該應用程序與項目和用戶(多對多)有關。經過身份驗證的用戶可以創建新項目。每個項目都有自己的頁面。在項目頁面上,會呈現一個列表,其中包含作為該項目成員的每個用戶的名稱,每個名稱旁邊都有一個按鈕,用于從該項目中刪除特定用戶/成員。現在,我陷入了“刪除用戶”功能。我不明白如何獲取列表中每個用戶的 id,并將其傳遞給將“分離”多對多關系的函數。我的文件如下:遷移:用戶表: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();    });}項目表: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');    });}項目_用戶_表(數據透視表):public function up(){    Schema::create('project_user', function (Blueprint $table) {        $table->foreignId('project_id')->constrained();        $table->foreignId('user_id')->constrained();        $table->timestamps();    });}型號:用戶.php:public function projects(){    return $this->belongsToMany('App\Project');}項目.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貢獻1809條經驗 獲得超8個贊

嘗試這個:


public function remove_user(Project $project, User $member)

{

? ? $project->members()->detach($member->id);

? ? return redirect('/projects/'.$project->id);

}

因為您在路線中傳遞了兩個參數。因此,您將獲得一個模型實例Project和一個User模型實例。然后只需訪問關系并訪問detach()方法$user->id即可完成工作。您可以通過在方法中傳遞 ids 數組來分離多個用戶,或者通過不帶參數detach()調用來從項目中刪除所有用戶。detach()



查看完整回答
反對 回復 2023-08-06
  • 1 回答
  • 0 關注
  • 114 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號