2015-01-11 34 views
3

我必須在Laravel中查詢。首先,獲得一個單一的職位。其次,要獲得所有評論。我的問題是,我無法在Laravel Query Builders中正確追加get()的兩個數組輸出。在Laravel中追加兩個數組get()Query Builders

當我試圖加入他們時,該帖子出現了3次,因爲我對該帖子有3條評論。所以,而不是加入我試圖array_push他們。現在輸出是這樣的。

[ 
    { 
    "id": 44, 
    "image": "9178hello.jpg", 
    "description": "Lorem ipsum dolor sit amit!", 
    "address": "internet", 
    "lat": 45.435, 
    "long": 2312.3, 
    "created_at": "1 hour ago" 
    }, 
    [ 
     { 
      "comment": "my comment.... my comment 1.....", 
      "created_at": "2015-01-11 17:24:27" 
     }, 
     { 
      "comment": "my comment.... my comment 2.....", 
      "created_at": "2015-01-11 17:24:29" 
     }, 
     { 
      "comment": "my comment.... my comment 3.....", 
      "created_at": "2015-01-11 17:24:30" 
     } 
    ] 
] 

我怎樣才能使它爲:

[ 
    { 
    "id": 44, 
    "image": "9178hello.jpg", 
    "description": "Lorem ipsum dolor sit amit!", 
    "address": "internet", 
    "lat": 45.435, 
    "long": 2312.3, 
    "created_at": "1 hour ago", 
    "comments" : { 
      list all the comments here... 
     } 
    } 
] 

這裏的查詢:

$disaster = Disaster::where('name', '=', $name)->first(['id']); 

    $post = DB::table('posts') 
       ->join('locations', 'locations.id', '=', 'posts.location') 
       ->join('users', 'users.id', '=', 'posts.user_id') 
       ->select('posts.id', 'posts.image', 'posts.description', 'locations.address', 'locations.lat', 'locations.long', 'posts.user_id', 'users.firstname', 'users.lastname', 'posts.created_at') 
       ->where('posts.disaster_id', '=', $disaster->id) 
       ->where('posts.id', '=', $id) 
       ->get(); 

    if (empty($post)) { 
     return ['error' => 'no post found']; 
    } 

    $post[0]->created_at = Carbon::parse($post[0]->created_at)->diffForHumans(); 

    $comments = DB::table('comments') 
        ->select('comment', 'created_at') 
        ->where('post_id', '=', $post[0]->id) 
        ->get(); 

    array_push($post, $comments); 

    return $post; 

回答

1

你能做到這一點做

$array = array_merge($post, array('comments' => $comments)); 

文檔:array_merge 這將追加t他對comments key發表了評論。

由於您使用的是Laravel,爲什麼不能使用Eloquent關係?只需在帖子和評論之間建立一對多的關係,並以任何你想要的方式得到它們。

閱讀Laravel Eloquent Relations