我试图获取每个主题的下一个和上一个项目(标题和图片),我将其用于下一个和上一个链接:
$currentUser = PostTranslation::find($post->id);
$previousUserID = PostTranslation::where('id', '<', $currentUser->id)->max('id');
$nextUserID = PostTranslation::where('id', '>', $currentUser->id)->min('id');
但它只是获取下一个和上一个链接ID,我需要获取它们的标题。我用过这个:
$previousUserID2 = PostTranslation::find($currentUser->id-1);
但是当id = 0
我收到错误时。
答案 0 :(得分:1)
如果您的数据集太大,则max和min会降低您的SQL速度。
您可以使用first
和orderby
来检索与查询约束匹配的第一个模型。
$currentUser = PostTranslation::find($post->id);
//order by descending order and take the first entry
$previousUser = PostTranslation::where('id', '<', $currentUser->id)->select('id','title')->orderby('id','desc')->first();
$previous_id=$previousUser ->id;
$previous_title=$previousUser ->title;
//order by ascending order and take the first entry
$nextUser = PostTranslation::where('id', '>', $currentUser->id)->select('id','title')->orderby('id','asc')->first();
$next_id=$nextUser ->id;
$next_title=$nextUser ->title;
答案 1 :(得分:-1)
我在控制器上使用的最后一个代码:
$previousUser = PostTranslation::join('posts', 'posts.id', '=', 'post_translations.post_id')
->where('posts.id', '<', $currentUser->id)
->select('posts.id','post_translations.title','post_image')
->orderby('posts.id','desc')
->where('post_translations.language', $language)
->first();