【问题标题】:Laravel complex Eloquent RelationshipLaravel 复杂的雄辩关系
【发布时间】:2020-05-30 16:18:08
【问题描述】:

我正在使用 Laravel 开发聊天功能

model 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 模型如下

ChattingRoom::getRoomUuid([1,2])

然后它返回 r1

ChattingRoom::getRoomUuid([1,2,3])

然后它返回 r2

谢谢

【问题讨论】:

    标签: mysql laravel eloquent eloquent-relationship


    【解决方案1】:

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

    【讨论】:

    • $room_uuid1=ChattingRoom::whereIn('user_id',[1,2])->select('room_uuid')->get();这将返回 r1 和 r2。
    • 你是对的,我怎么错过了!..无论如何..我已经更新了我的答案。如果有帮助,请告诉我
    猜你喜欢
    • 1970-01-01
    • 2014-01-16
    • 2015-09-27
    • 2021-02-05
    • 2015-03-14
    • 2018-11-28
    • 2015-01-11
    • 2021-06-03
    • 2020-03-26
    相关资源
    最近更新 更多