2015-04-03 55 views
0

例如,我有查詢:Laravel 5 - 獲取查詢生成器,結果被列編組

$posts = DB::table('posts')->select(['id', 'user_id', 'title'])->get(); 

然後$posts陣列看起來像這樣:

array(3) { 
    [0]=> 
    object(stdClass) (3) { 
    ["id"]=> 
    int(1) 
    ["user_id"]=> 
    int(1000) 
    ["title"]=> 
    string(8) "Post # 1" 
    } 
    [1]=> 
    object(stdClass) (3) { 
    ["id"]=> 
    int(2) 
    ["user_id"]=> 
    int(2000) 
    ["title"]=> 
    string(8) "Post # 2" 
    } 
    [2]=> 
    object(stdClass) (3) { 
    ["id"]=> 
    int(3) 
    ["user_id"]=> 
    int(2000) 
    ["title"]=> 
    string(8) "Post # 3" 
    } 
} 

正如你可以看到用戶與id 1000有1帖子,用戶id 2000有2個帖子。

我想獲得的結果關聯數組user_id爲鍵:

array(2) { 
    [1000]=> 
    array(1) { 
    [0]=> 
    object(stdClass) (3) { 
     ["id"]=> 
     int(1) 
     ["user_id"]=> 
     int(1000) 
     ["title"]=> 
     string(8) "Post # 1" 
    } 
    } 
    [2000]=> 
    array(2) { 
    [1]=> 
    object(stdClass) (3) { 
     ["id"]=> 
     int(2) 
     ["user_id"]=> 
     int(2000) 
     ["title"]=> 
     string(8) "Post # 2" 
    } 
    [2]=> 
    object(stdClass) (3) { 
     ["id"]=> 
     int(3) 
     ["user_id"]=> 
     int(2000) 
     ["title"]=> 
     string(8) "Post # 3" 
    } 
    } 
} 

有沒有什麼好的解決辦法Laravel執行此?

回答

1

您可能想要查看Eloquent Relationships而不是使用查詢生成器。在你的情況下,你有一個一對多的關係。所以,你就會有一個User模型看起來是這樣的:

class User extends Model { 

    public function posts() 
    { 
     // One User can have many Posts 
     return $this->hasMany('App\Post'); 
    } 

} 

並有Post模型:

class Post extends Model { 

    public function user() 
    { 
     // A Post belongs to one User 
     return $this->belongsTo('App\User'); 
    } 

} 

然後你可以得到用戶的帖子是這樣的:

$users = User::all(); 

foreach ($users as $user) 
{ 
    $posts = $user->posts; 

    // $posts will now contain a Collection of Post models 
} 
+0

我絕對應該重構已存在的模型以雄辯,謝謝! – 2015-04-03 13:03:57

0

Laravel沒有辦法做到這一點。但是你可以使用此功能手動執行此操作:

public static function makeAssocArrByField($arr, $field) 
{ 
    $assocArr = array(); 
    foreach($arr as $arrObj) 
    { 
     if(isset($arrObj[$field])) 
      $assocArr[$arrObj[$field]] = $arrObj; 
    } 

    return $assocArr; 
} 

調用方法爲:

$posts = makeAssocArrByField($posts, 'user_id'); 

這將返回數組,按您的需要的格式。