0

In the following very simplified example and study case, we get the list of posts and the count of comments for each post.

However, I intended to send to client side only the value, i.e. 2, and not the array object [{total: 2}]

Is there a simplified way to do this with the laravel?

Note: DB::select must be used

public function readPosts(Request $request) {     
    $posts = DB::select("SELECT * FROM posts");   

     foreach ($posts as $key => $post) {         
         $idComment = $post->id_comment;             
         $post->nComments = DB::select('SELECT COUNT(id_comment) As total FROM post_comments WHERE id_comment = ? ', [$idComment]); 
     }    

    if($posts){
      return response()->json(['success'=>true, "output"=>$posts);
    }else{
      return response()->json(['success'=>false]);  
    }
}

response

data:
    0:
      id_post: 1
      post: "post text"
      nComments: [{total:2}]
   1:
      id_post: 2
      post: "post text 2"
      nComments: [{total:1}]

Expected

data:
    0:
      id_post: 1
      post: "post text"
      nComments: 2
    1:
      id_post: 2
      post: "post text 2"
      nComments: 1
1
  • Did you declare the relation comments() in the Post model or you need help with that ? Commented Jan 7, 2020 at 13:24

5 Answers 5

1

I suggest that you can use Eloquent with eager loading to get the count. However you need to reconstruct your tables, and build relationship with your models.

If you really want to use DB::select(),

You can just use subquery

$posts = DB::select('
SELECT posts.*, (
    SELECT COUNT(id_comment)  AS total
    FROM post_comments 
    WHERE id_comment = posts.id_comment) AS total
FROM posts')
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks TsaiKoga. wihCount is a great solution and perhaps best suited for this type of case. However, in my real (more complex) problem I necessarily have to use DB :: select
@josei man, really really suggest you rebuild the table structure.
Thanks TsiKoga. It's just a simplified fictional case to illustrate the problem I want to solve. With eloquent and relationship, as you suggest, it would be very simple and effective. But it really has to be with DB: select this case. I am trying to find a simple solution with laravel that does not go through the model.
Thanks TsaiKoga. Your suggestion is very interesting and a simple solution that works well (for my very specific case where there is no model). Thanks again.
1

you can try this

 public function readPosts(Request $request) {     
            $posts = DB::select("SELECT * FROM posts");   

             foreach ($posts as $key => $post) {         
                 $idComment = $post->id_comment; 
                 $total = DB::select('SELECT COUNT(id_comment) As total FROM post_comments WHERE id_comment = ? ', [$idComment]);        
                 $post->nComments = $total[0]['total'];
             }    

            if($posts){
              return response()->json(['success'=>true, "output"=>$posts);
            }else{
              return response()->json(['success'=>false]);  
            }
        }

1 Comment

Thnaks Vicky. I tried your solution, but it didn't work in that case.
1

Cleanest way would be to use the relations comments of the post

public function readPosts(Request $request) {     
    $posts = DB::withCount('comments')->get();   

    if($posts){
      return response()->json(['success'=>true, "output"=>$posts);
    }else{
      return response()->json(['success'=>false]);  
    }
}

response

data:
    0:
      id_post: 1
      post: "post text"
      comments_count: 2
   1:
      id_post: 2
      post: "post text 2"
      comments_count: 1

Plus: this will take advantage of the eager loading in Eloquent and the results will be way faster and performant.

Comments

1

Try this simple

 $posts = Post::withCount('comments');  
 dd($post);

1 Comment

Thnaks Vikas. In my real (more complex) problem I necessarily have to use DB :: select
1

You can use count() for the collections count.

 foreach ($posts as $key => $post) {         
         $idComment = $post->id_comment;             
         $comments = DB::select('SELECT COUNT(id_comment) As total FROM post_comments WHERE id_comment = ? ', [$idComment]); 
         $post->nComments = $comments[0]['total'];
     }    

1 Comment

Thanks Adnan. I tried this solution but with ->count() i get de error message "Call to a member function count() on array"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.