php - Laravel Eloquent : Get record that contains two specific relations

标签 php laravel laravel-5 eloquent has-and-belongs-to-many

我有一个项目,用户可以在其中与其他用户创建对话。对话可以 belongsToMany用户和用户可以belongsToMany对话。

我现在需要获得两个特定用户参与的对话。

我尝试了使用 whereIn 的解决方案组合我尝试了以下方法:

$c = Conversation::whereHas('users', function($q)
     {
         $q->whereIn('user_id', array(1,3));
     })
    ->get();

这里的问题是whereIn('user_id', [1,3])获取包含 1 或 3 的记录。我需要它返回包含 1 和 3 的记录。

session 模型
class Conversation extends Model {

    public function users(){
        return $this->belongsToMany('App\User');
    }
}

用户模型
class User extends Model {

    public function conversations(){
        return $this->belongsToMany('App\Conversation');
    }

}



对话:

身份证 |主题

对话用户:

身份证 |用户 ID |对话_id

来自表conversation_user的数据

enter image description here

最佳答案

你最新的编辑更有意义,这实际上是一个非常简单的修复。 whereHas需要两个额外的参数来查找计数。

$users = [1, 3];   

$c = Conversation::whereHas('users', function($q) use ($users)
{
    $q->whereIn('user_id', $users);
}, '>', count($users) )
->get();

这将获得用户 1 和 3 参与的所有对话,即使还有其他用户参与了这些对话。如果您只想与用户 1 和 3 进行对话,请更改 >= .

编辑:我刚刚意识到你的数据透视表有一个 id柱子。如果您的数据透视表将有重复项,则此方法可能不起作用。例如,如果您两次使用相同的 session_id 两次 user_id 为 1,即使它在技术上只有 1 个用户,它也会返回该 session 。我建议删除 id列并创建复合主键 user_idconversation_id .如果存在重复的可能性,使用 lukasgeiter 的解决方案可能更安全。

关于php - Laravel Eloquent : Get record that contains two specific relations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30192408/

相关文章:

php - Laravel 5.4 MethodNotAllowedHttpException

php - 在上一次调用成功之前阻止 ajax 脚本执行

php - 如何从 Iframe 获取父页面信息并使用该信息在 Iframe 中显示 PHP 页面

php - 为什么本地主机在重定向时收到 HTTP 500 错误?

php - WooCommerce 缺少 WC_Subscriptions_Manager::prepare_renewal() 的参数 1

php - Laravel API 请求验证

php - 使用 laravel 的站点地图

mysql - Laravel Eloquent ORMWhere 语句在默认的created_at时间戳上进行日期时间戳比较

php - Laravel 5.1 在数据库表的前面添加 MySQL 列

php - Laravel 查询生成器 : MySQL 'LIKE' inside a multiple where conditioned query