Laravel 5.6-如何从非关系表中获取发布数据?

时间:2018-07-02 18:01:58

标签: php mysql laravel laravel-5.6

我正在使用Laravel 5.6。我桌子的下方

表:类别

+----+-----------+----------+
| id | name      |  slug    |
+----+-----------+----------+
|  1 | Cat1      | cat1     |
|  2 | Cat2      | cat2     |
|  3 | Cat3      | cat3     |
+----+-----------+----------+

表格:帖子

+----+----------+------------+----------+
| id | user_id  | name       |  photo   |
+----+----------+------------+----------+
|  1 | 1        | Post1      | img1.jpg |
|  2 | 2        | Post2      | img2.jpg |
|  3 | 1        | Post3      | img3.jpg |
|  4 | 1        | Post4      | img4.jpg |
+----+----------+------------+----------+

表格:post_categories

+----+----------+--------------+
| id | post_id  | category_id  |
+----+----------+--------------+
|  1 | 1        | 1            |
|  2 | 1        | 2            |
|  3 | 1        | 3            |
|  4 | 2        | 1            |
|  5 | 2        | 3            |
|  6 | 3        | 3            |
|  7 | 4        | 2            |
+----+----------+--------------+

以上,我已经张贴了我的3张桌子。这是post_categories表与postscategories表的关系。我想明智地显示所有帖子类别。下面看到我的输出如下:

Cat1
   Post1
   Post2
Cat2
   Post1
   Post4
Cat3
   Post1
   Post2
   Post3

URL:

  
    

http://chhayalsing.com/blog

         

http://chhayalsing.com/blog/category/people

  

N.B:如果您要阅读我们的当地语言。您能否将语言Odia更改为English(页脚部分中存在“更改语言”选项)

People个类别,共有8个帖子。但是这里展示了所有。我对此查询一无所知。我尝试过:

$posts = Post::with([
    'user' => function($query) {
        $query->select(['id', 'username']);
    }, 
    'comments', 
    'post_category' => function($query) {
        $query->select(['id', 'name']);
    }
])->where('status', '=', 1)
->orderBy('id', 'DESC')->paginate($perPage);

我知道我的代码是错误的。但是我对这个框架完全陌生。无法做到这一点。您能为我提供分页查询以获取帖子列表吗?

1 个答案:

答案 0 :(得分:0)

您可以轻松查询以获取所有类别$cats = Cat::all()。然后,使用循环获取每个类别$cat的所有帖子,并将其推送到$cats的孩子中。

最后,您将只有一个元素(可能是$cats)。看起来像这样:

$cat = { items: array:2[ 1 => { "id": "1", "name": "cat1:, "post": array:3 [ 1 => post1 detail, 2 => post2 detail, 3 => post3 detail ] }, 2 => { "id": "2", "name": "cat2:, "post": array:2 [ 1 => post1 detail, 2 => post2 detail, ] } }

然后,在刀片服务器中,仅使用$ cats可以帮助您传递有关$ cat和ifself的$ post的所有数据。