Nic*_*ank 4 php has-and-belongs-to-many laravel eloquent laravel-5
我有一个项目,用户可以在其中与其他用户创建对话。用户可以进行对话belongsToMany,用户可以belongsToMany进行对话。
我现在需要获取两个特定用户参与的对话。
我尝试了多种解决方案的组合whereIn,并尝试了以下方法:
$c = Conversation::whereHas('users', function($q)
{
$q->whereIn('user_id', array(1,3));
})
->get();
Run Code Online (Sandbox Code Playgroud)
这里的问题是获取包含whereIn('user_id', [1,3])1 或 3的记录。我需要它返回包含1和 3 的记录。
对话模型
class Conversation extends Model {
public function users(){
return $this->belongsToMany('App\User');
}
}
Run Code Online (Sandbox Code Playgroud)
用户模型
class User extends Model {
public function conversations(){
return $this->belongsToMany('App\Conversation');
}
}
Run Code Online (Sandbox Code Playgroud)
表格
对话:
编号 | 主题
对话用户:
编号 | 用户 ID | 对话id
来自表conversation_user的数据

您的最新编辑更有意义,这实际上是一个非常简单的修复。 whereHas需要两个附加参数来查找计数。
$users = [1, 3];
$c = Conversation::whereHas('users', function($q) use ($users)
{
$q->whereIn('user_id', $users);
}, '>', count($users) )
->get();
Run Code Online (Sandbox Code Playgroud)
这将获取用户 1 和 3 参与的所有对话,即使还有其他用户参与了这些对话。如果您只想与用户 1 和 3 进行对话,请将 更改>为=.
编辑:我刚刚意识到你的数据透视表有一id列。如果您的数据透视表有重复项,则此方法可能不起作用。例如,如果您的 user_id 为 1 两次,且两次对话 ID 相同,则即使技术上只有 1 个用户,它也会返回该对话。我建议删除该列并创建和id的复合主键。如果存在重复的可能性,使用 lukasgeiter 的解决方案可能会更安全。user_idconversation_id