gpt4 book ai didi

mysql - 需要帮助将嵌套连接查询转换为 Laravel Eloquent

转载 作者:行者123 更新时间:2023-11-29 21:41:11 25 4
gpt4 key购买 nike

需要一些帮助才能在 Laravel 中进行查询。

我在 Laravel 之外尝试过这个查询,它有效:

SELECT t.*
FROM
stories AS t
JOIN
( SELECT created_at
FROM stories
WHERE id = 126
) AS o
ON t.created_at = o.created_at AND t.id > 126
OR t.created_at < o.created_at
ORDER BY
t.created_at DESC LIMIT 30;

说明:基本上分页需要它,因为当用户转到下一页时,它会向他们显示在指定 id 之前创建的 30 个故事。当我按created_at 对故事进行排序时,它们会变得随机,因此我需要在通过上述查询完成的特定行之后获取接下来的 30 行。126是上一页最后一个故事的id,在实际代码中将是一个变量。

因此,当我尝试在 Laravel Eloquent 中使用它时,无论我做什么,我都无法使其工作。

我已经尝试过

$result = App\Story::join(DB::table('stories AS last_story')->find($previous_last_post_id), function($join)
{
$join->on('stories.created_at', '=', 'last_story.created_at')
->where('stories.id', '>', 'last_story.id')
->orWhere('stories.created_at', '<', 'last_story.created_at');
})
->get()

这给了我

ErrorException in Grammar.php line 39: Object of class stdClass could not be converted to string

将子查询更改为

DB::table('stories AS last_story')->where('id', $previous_last_post_id)->get()

给我:

ErrorException in Grammar.php line 39: Array to string conversion

放弃并尝试原始查询:

$result = DB::select("SELECT t.*
FROM
stories AS t
JOIN
( SELECT created_at
FROM stories
WHERE id = 126
) AS o
ON t.created_at = o.created_at AND t.id > 126
OR t.created_at < o.created_at
ORDER BY
t.created_at DESC LIMIT 30")

但这给了我

FatalErrorException in e969125ed5dcf92ec33b84157c0eb37a line 88: Call to a member function toFormattedDateString() on string

最佳答案

尝试使用 first(),而不是返回数组的 get()

关于mysql - 需要帮助将嵌套连接查询转换为 Laravel Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34482220/

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