「ユーザーが多数のプロジェクトに参加しており、かつプロジェクトに多数のユーザーが参加している」
という多対多のリレーションで、
ログイン中のユーザーがそのプロジェクトに参加中かどうかの判定はどのようにしたら良いのでしょうか。
php
1 public function join($id){ //$id は参加したいプロジェクトのid 2 $user = Auth::user(); 3 $user->projects()->attach($id); 4 return redirect('projects'); 5 }
中間テーブルの project_id
、 user_id
をユニークな複合キーとしているため、
上記のメソッドを、すでに参加中のプロジェクトのidで呼び出すと
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-2' for key 'project_user_user_id_project_id_unique' (SQL: insert into `project_user` (`project_id`, `user_id`) values (2, 1))
こちらのエラーが出ます。
これを防ぐために、すでに関係がある場合は $user->projects()->attach($id);
をする前にreturnしたいのですが...
php
1# app/Project.php 2namespace App; 3 4use App\User; 5use Illuminate\Database\Eloquent\Model; 6 7class Project extends Model 8{ 9 public function users() { 10 return $this->belongsToMany(User::class); 11 } 12}
php
1# app/User.php 2namespace App; 3 4use Illuminate\Notifications\Notifiable; 5use Illuminate\Foundation\Auth\User as Authenticatable; 6 7class User extends Authenticatable 8{ 9 use Notifiable; 10 public function projects() { 11 return $this->belongsToMany(Project::class); 12 } 13}
mysql> show columns from project_user; +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | user_id | int(10) unsigned | NO | MUL | NULL | | | project_id | int(10) unsigned | NO | MUL | NULL | | +------------+------------------+------+-----+---------+----------------+
初心者です。不足情報等ありましたらおしえてください。
asahina1979さん
ありがとうございます。
mysql> show columns from project_user; +------------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+-------+ | user_id | int(10) unsigned | NO | PRI | NULL | | | project_id | int(10) unsigned | NO | PRI | NULL | | +------------+------------------+------+-----+---------+-------+
php
1if ($user->projects()->where('project_id', $id)->exists()) { 2 // 3}
これで関係の存在がチェックできることがわかったのですが、
一般的な書き方があれば教えてほしいです。
回答1件
あなたの回答
tips
プレビュー