【发布时间】:2016-04-01 15:15:30
【问题描述】:
需要一些帮助才能在 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()
这给了我
Grammar.php 第 39 行中的 ErrorException:stdClass 类的对象无法转换为字符串
将子查询更改为
DB::table('stories AS last_story')->where('id', $previous_last_post_id)->get()
给我:
Grammar.php 第 39 行中的 ErrorException:数组到字符串的转换
放弃并尝试原始查询:
$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")
但这给了我
e969125ed5dcf92ec33b84157c0eb37a 第 88 行中的 FatalErrorException:调用字符串上的成员函数 toFormattedDateString()
【问题讨论】:
标签: mysql laravel laravel-5 eloquent laravel-5.1