使用Laravel 5.5
假设我有一个User表和Conversation表,它们与ManyToMany关系有关。
用户
id用户
1 A
2 B
3 C
4 D
会话
id title
1 Conv1
2 Conv2
用户A,B和C与Conv1
相关联用户B,C和D与Conv2相关联。
如果用户想要创建新的对话并选择A,B和C
如何验证与这些用户的对话以及仅存在这些用户?
public function postThread() {
$thread = new Thread;
$thread->title = request()->get('name');
$thread->type = request()->get('type');
/* How to verify if Thread exists with and only with all the users in request()->get('users') */
Auth::user()->threads()->save($thread); //creates relation with new thread
foreach (request()->get('users') as $user) {
$user = User::find($user);
$user->threads()->save($thread);//creates relation with every user with new thread
}
$thread->save();
return $thread;
}
答案 0 :(得分:1)
现在无法测试,但应该可以工作(仍然效率不高)
$users = $request->get('users');
$user = Auth::user();
$validThreads = $user->threads()->whereHas('users', function($query) use ($users){
foreach( $users as $user_id) {
$query->where('user_id',$user_id);
}
});
// Valid threads is a collection of threads where all the users are present, now we need to check that no more users are present in that thread
$totalUsers = count($users)+1;
$thread = $validThreads->filter(function($thread) use ($totalUsers){
return $thread->users()->count() == $totalUsers;
})->first();
if (is_null($thread)) {
// The thread does not exists
}