首页 > 解决方案 > 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

谢谢

标签: mysqllaraveleloquenteloquent-relationship

解决方案


你可以使用 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

还:

https://stackoverflow.com/a/45592687/10573560


推荐阅读