简体   繁体   English

在laravel获得下一个和上一个条目

[英]get next and previous entry in laravel

I'm trying to get the next and previous items (title and image) for each topic and I have this for next and previous links: 我正在尝试获取每个主题的下一个和上一个项目(标题和图像),我将其用于下一个和上一个链接:

$currentUser = PostTranslation::find($post->id);

$previousUserID = PostTranslation::where('id', '<', $currentUser->id)->max('id');

$nextUserID = PostTranslation::where('id', '>', $currentUser->id)->min('id');

but it's just get the next and previous link id, which I need to get the title for them too. 但它只是得到下一个和上一个链接ID,我需要获得它们的标题。 I have used this: 我用过这个:

$previousUserID2 = PostTranslation::find($currentUser->id-1);

but it's when id = 0 that I am getting an error. 但是当id = 0 ,我收到了一个错误。

If your dataset is too big max and min can slow down your sql. 如果你的数据集太大,max和min会降低你的sql速度。

You can use first along with orderby which retrieve the first model matching the query constraints. 您可以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;

That's last code i have been used at my controller : 这是我在我的控制器上使用的最后一个代码:

$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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM