简体   繁体   English

如何在不使用 Eloquent 的情况下在 Laravel 中使用多表查询

[英]How to use Multi table queries in Laravel without using Eloquent Relationships

I am using Laravel to create API for my app, later it will be integrated with react front-end.我正在使用 Laravel 为我的应用程序创建 API,稍后它将与反应前端集成。 I have two tables, Post & Comment.我有两张表,发布和评论。 Post table contains info about posts & comment table contains the comments data about each post.帖子表包含有关帖子的信息,评论表包含有关每个帖子的评论数据。 Below is there structure,下面是结构,

  • Post Table发布表

post_id (Primary Key) post_title post_description post_id(主键) post_title post_description

  • Comment Table评论表

comment_id (Primary Key) comment_text post_id (Foreign Key) comment_id(主键) comment_text post_id(外键)

I need to take post_id, post_title from post table and total no of comments on each post from comment table & want the json data to be showed like this我需要从帖子表中获取 post_id、post_title 以及评论表中每个帖子的总评论数,并希望 json 数据像这样显示

        {
            "post_id": 1,
            "post_title": "some title",
            "total comments": "4"

        },

I know how to write sql queries for these but just having issue with showing the data like the above.我知道如何为这些编写 sql 查询,但只是在显示上述数据时遇到问题。 Below is the code which I am using.下面是我正在使用的代码。

$allPostQuery= DB::select('select * from post');

foreach($allPostQuery as $allPostQuery)

{

$postId= $allPostQuery->post_id;

$totalCommentsQuery= DB::select('select count(comment_id) as totalComments from comment where post_id=:postId',["postId" => $postId ]);

}

return \Response::json([$allPostQuery,$totalCommentsQuery]);

But thats not working.但这不起作用。 I am confused about the looping of post ids to get total comments for each post.我对循环发布帖子 ID 以获得每个帖子的总评论感到困惑。 Do I have to do this in front-end using react foreach loop?我是否必须在前端使用 react foreach 循环来执行此操作? Anyone can suggest any help.任何人都可以提出任何帮助。 Thanks谢谢

As per your question you just need the Post ID, TITLE and Count of the Comments of each posts:根据您的问题,您只需要每个帖子的帖子 ID、标题和评论数:

    $query = DB::select('
        SELECT 
            p.post_id, 
            p.title, 
            c.total AS totla_comments
        FROM posts p
        INNER JOIN 
        (
            SELECT post_id, COUNT(post_id) AS total FROM comments WHERE comments.post_id = post_id
            GROUP BY post_id

        ) c
        ON p.post_id = c.post_id
    ');

    echo json_encode($query);

Use json_encode (Laravel has ->json() function) if you want the data return should be in JSON format.如果您希望数据返回应为 JSON 格式,请使用json_encode (Laravel 有->json()函数)。

Looking at your approach:看看你的方法:

  1. First you query the post首先你查询帖子
  2. You loop the post again and query the comments您再次循环帖子并查询评论

This will impact your performance speed and should be avoided.这将影响您的性能速度,应该避免。

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

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