gpt4 book ai didi

php - Eloquent 查询构建器 if 子句实现

转载 作者:行者123 更新时间:2023-11-29 19:05:34 27 4
gpt4 key购买 nike

我有一个这样的查询

        SELECT
`id`,
`advert_id`,
IF(
`chats`.`owner_id` = ?,
`chats`.`sender_id`,
`chats`.`owner_id`
) AS `sender_id`,
IF(
`chats`.`owner_id` = ?,
`chats`.`owner_access_time`,
`chats`.`sender_access_time`
) AS `access_time`,
`created_time`
FROM
`chats`
WHERE 1
AND `id` = ?
AND `owner_id` = ?
AND `project_id` = ?
UNION
SELECT
`id`,
`advert_id`,
IF(
`chats`.`owner_id` = ?,
`chats`.`sender_id`,
`chats`.`owner_id`
) AS `sender_id`,
IF(
`chats`.`owner_id` = ?,
`chats`.`owner_access_time`,
`chats`.`sender_access_time`
) AS `access_time`,
`created_time`
FROM
`chats`
WHERE 1
AND `id` = ?
AND `sender_id` = ?
AND `project_id` = ?
ORDER BY `id` ASC

我正在尝试使用这样的 Eloquent 查询构建器来实现它

    $chats = $database
->table('chats')
->where('sender_id', '=', $arguments['user_id'])
->union(
$database
->table('chats')
->where('owner_id', '=', $arguments['user_id'])
->get(
[
'advert_id',
'owner_id',
'sender_id',
'id'
]
)
)
->get(
[
'advert_id',
'owner_id',
'sender_id',
'id'
]
);

但是我收到错误方法 getBindings 不存在。,而且我找不到如何用 Eloquent 方式编写“if”子句,我找到的只是when方法,但据我了解,它仅适用于“如果存在参数,请在查询中添加附加子句”,这不是我需要的。

最佳答案

解决方案

    $chats = $database::table('chats')
->where('sender_id', '?')
->select(
'id',
'advert_id',
$database::raw('
IF(
`chats`.`owner_id` = ?,
`chats`.`sender_id`,
`chats`.`owner_id`
) AS `sender_id`
'),
$database::raw('
IF(
`chats`.`owner_id` = ?,
`chats`.`owner_access_time`,
`chats`.`sender_access_time`
) AS `access_time`
')
)
->setBindings(
[
$arguments['user_id'],
$arguments['user_id'],
$arguments['user_id'],
]
)
->union(
$database::table('chats')
->where('owner_id', '?')
->select(
'id',
'advert_id',
$database::raw('
IF(
`chats`.`owner_id` = ?,
`chats`.`sender_id`,
`chats`.`owner_id`
) AS `sender_id`
'),
$database::raw('
IF(
`chats`.`owner_id` = ?,
`chats`.`owner_access_time`,
`chats`.`sender_access_time`
) AS `access_time`
')
)
->setBindings(
[
$arguments['user_id'],
$arguments['user_id'],
$arguments['user_id'],
]
)
)
->get();

关于php - Eloquent 查询构建器 if 子句实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43541976/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com