mysql - Laravel 复杂的雄辩关系
问题描述
我正在使用 Laravel 开发聊天
模型 ChattingRoom 具有以下属性:
$table->uuid('room_uuid');
$table->integer('user_id');
有类似的项目
room_uuid, user_id
r1, 1
r1, 2
r2, 1
r2, 2
r2, 3
r3, 2
r3, 3
房间 r1 有用户 1,2。
房间 r2 有用户 1,2,3。
房间 r3 有用户 2,3。
我想获得具有用户 1 和 2 的 room_uuid。我还想获得具有用户 1、2、3 的 room_uuid。
我做了如下查询
with step0 as (
select room_uuid,0 as cnt
from chatting_rooms
where user_id = 1),
step1 as (
select room_uuid, 0 as cnt
from chatting_rooms
where user_id = 2
),
step2 as (
select room_uuid, count(room_uuid) as cnt from chatting_rooms group by room_uuid having cnt =2
)
select step0.room_uuid
from step0,
step1,
step2
where step0.room_uuid = step1.room_uuid and step2.room_uuid = step0.room_uuid;
我想使用 ChattingRoom 模型如下
聊天室::getRoomUuid([1,2])
然后它返回 r1
聊天室::getRoomUuid([1,2,3])
然后它返回 r2
谢谢
解决方案
你可以使用 whereIn ... $values=[1,2]'
$room_uuid1=ChattingRoom::whereIn('user_id',$values)
->groupBy('chatting_rooms.user_id')
->having(DB::raw('count(*)'), '=', count($values))
->select('room_uuid')->get();
有关 whereIn 的更多详细信息:
https://laravel.com/docs/7.x/queries#where-clauses
还:
推荐阅读
- jquery - Jquery 无法运行,如何检查错误?
- vuejs2 - Stripe redirectToCheckout 方法在 .then 部分显示任何响应之前重定向到成功的 url
- javascript - 禁用/重新启用 safari 扩展时如何防止多次注入内容脚本?
- javascript - 按数组 2 的 ID 对数组 1 进行排序。根据数组 2 从数组 1 中删除和添加元素时
- c# - MediaPlayerElement 不播放视频,除了不从我的可移动设备中获取路径
- docker - 未定义时,Docker Compose env 文件优先于 shell 传递变量
- python-2.7 - 如何验证对 AWS 签名 v4 的支持?
- firebase - Cloud Functions 部署失败:“加载用户代码时函数失败。错误消息:无法加载文件 lib/index.js 中的代码。”
- amazon-web-services - Nodejs 应用程序未连接到亚马逊 ecs 任务定义中的 redis。getaddrinfo ENOTFOUND redis redis:6379
- java - 无法从 Mapbox FeatureCollection 获取地址