简体   繁体   中英

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. 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

  • Comment Table

comment_id (Primary Key) comment_text post_id (Foreign Key)

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": 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. 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. Do I have to do this in front-end using react foreach loop? 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:

    $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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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