简体   繁体   English

通过关系命令分页(Laravel 5.3)

[英]Ordering a pagination by a relationship (Laravel 5.3)

In my app I have posts. 在我的应用程序中,我有帖子。 I wish to show all the posts on the homepage, but order them higher if the post's user has uploaded an image. 我希望在首页上显示所有帖子,但如果帖子的用户已上传图片,则将其排序更高。 I can determine if the post's user has uploaded an image by checking if the user has a relationship with a row in the images table, like this: 我可以通过检查用户是否与images表中的一行有关系来确定帖子的用户是否上传了图片,如下所示:

$post->user->image 

My code currently looks like this: 我的代码当前如下所示:

$posts = Post::where('subject_id', '=', $subject->id)
        ->approved()
        ->orderBy('created_at', 'desc')
        ->paginate(18);

Currently, I am simply ordering it by created at, but ideally all posts whose related user has an image will come first, then the rest. 目前,我只是按创建者的顺序对其进行排序,但理想情况下,其相关用户具有图像的所有帖子都将排在第一位,然后是其余部分。 I've been looking for a way to do this efficiently and in a way that doesn't just work on the first page. 我一直在寻找一种有效地做到这一点的方法,并且这种方法不仅仅在首页上起作用。

How should I go about this? 我应该怎么做?

Try this: 尝试这个:

$posts = Post::where('subject_id', '=', $subject->id)
        ->approved()
        ->select(['*', DB::raw('(SELECT count(images.id) FROM images INNER JOIN users ON users.image_id = images.id WHERE posts.user_id = users.id) as count_images'])
        ->orderBy('count_images', 'desc')
        ->orderBy('created_at', 'desc')
        ->paginate(18);

Try this: 尝试这个:

$posts = Post::where('subject_id', '=', $subject->id)
         ->approved()
         ->with('user')
         ->join('users', 'users.id', '=', 'post.user_id')
         ->select(['post.*', 'users.avatar'])
         ->orderBy('image', 'desc')
         ->orderBy('created_at', 'desc') // ->latest() can be used for readability
         ->paginate(18);

This code eager loads users to reduce number of DB queries and doesn't use raw queries which should be avoided, because mistake can make your application vulnerable to SQL injection. 此代码渴望使用户减少数据库查询的数量,并且不使用应避免的原始查询,因为错误会使您的应用程序容易受到SQL注入的攻击。

Explanation: 说明:

We eager load relationship using ->with('user') method, then join users table, select all fields from posts table and only image field from users table, then order results by image and paginate results. 我们渴望使用-> with('user')方法加载关系,然后联接users表,从posts表中选择所有字段,并从users表中仅选择image字段,然后按图像和分页结果排序结果。

Result should look like this: 结果应如下所示:

App\\Post: 应用程序\\帖子:

  • id ID
  • title 标题
  • ... ...
  • image(from users table) 图片(来自用户表)
  • App\\User (eager loaded relationship) 应用\\用户 (渴望加载的关系)
    • id ID
    • name 名称
    • email 电子邮件
    • ... ...
    • image 图片
    • created_at created_at

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

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