簡體   English   中英

Laravel leftJoin無法正確返回

[英]Laravel leftJoin not return correctly

我對使用larateJoin的laravel select有問題。 我正在嘗試選擇2個帖子並計算有多少評論(第一個帖子有7條評論,第二個-0),但是我只有第一條有7條評論。

代碼是:

$posts = DB::table('posts')
        ->leftJoin('comments', 'comments.post', '=', 'posts.id')
        ->select(DB::raw('posts.title, posts.body, posts.created_at, posts.slug, CASE WHEN comments.post IS NULL THEN 0 WHEN comments.post IS NOT NULL THEN count(comments.post) END as count'))
        ->get();

當我嘗試檢查在網絡瀏覽器中看到的內容時,出現錯誤: Call to a member function count() on a non-object

我在使用@if($posts->count())行的視圖文件中出現此錯誤

我調試過使用print_r()只能得到一個帖子。

有什么建議么?

我認為您最好的選擇是使用laravel的Eloquent ORM的一些內置功能。

在模型中建立關系:

post.php中:

<?php

class Post extends Eloquent {

   protected $table = 'posts';

   public function comments()
   {
      return $this->hasMany('Comment', 'posts');//first param refrences the other model, second is the foreign key
   }

Comment.php:

<?php

class Comment extends Eloquent {

   protected $table = 'comments';

   public function comments()
   {
      return $this->belongsTo('Post');//first param refrences the other model, second is unnecessary if you are using auto incrementing id
   }

現在您已經建立了關系,並且不需要加入。

用法:

也許有更好的方法可以做到這一點,但這應該可行。

  $posts = Post::with('comments')->get();//retrieves all posts with comments
   foreach($posts as $post){
     $count = count($post['comments']);
     $post['comment_count'] = $count;
  }
  return $posts;

這將返回包含所有帖子的結果,其中一個名為“ comments”的字段包含所有相關評論的數組。 “ comment_count”字段將包含計數。

例:

[
  {
   "id": 1,
    "created_at": "2014-07-02 11:34:00",
    "updated_at": "2014-07-02 11:34:00",
    "post_title": "hello there",
    "comment_count": 1,
    "comments": [
        {
          "id":'blah'
          "comment_title":"blah"
        }
     ]

}

您現在可以將其傳遞到視圖並遍歷每個帖子,並獲得$post['comment_count']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM