2016-04-14 11 views
1

Laravel 5.1を使用してwithの関係から単一の列を返そうとしています。すべてのカテゴリを取得したいと思います。それぞれには、関連する質問IDの配列(完全な質問オブジェクトではありません)があります。空の配列を返す "with"のSelect文

$categories = Category::with(['questions'])->get();は質問オブジェクトの配列ですべてのカテゴリを取得できます。これは私が望むものではありません。私は質問IDだけを必要とします。

this post後、私が選択するためのネストされたクエリを追加しました:

$categories = Category::with(['questions'=>function($query){ 
     $query->select('id'); 
    }])->get(); 

予想通りこれは、すべてのカテゴリを返しますが、各カテゴリに属する​​すべての「質問」配列は空です。

私も自分のモデルを編集して試してみた:

public function questions() 
{ 
    return $this->hasMany('App\Question')->select('id'); 
} 

これはなぜでしょうか?

モデル

質問モデル:

public function category() 
{ 
    return $this->belongsTo('App\Category'); 
} 

カテゴリーモデル:

public function questions() 
{ 
    return $this->hasMany('App\Question'); 
} 

同様に、私は実際のSQLをログに記録するmysql query loggerを使用しています。ネストされた$query 1は予想通り、私はIDを選択しています私に語った

2016-04-14T04:54:04.777132Z 181 Prepare select * from `categories` 
2016-04-14T04:54:04.777230Z 181 Execute select * from `categories` 
2016-04-14T04:54:04.777566Z 181 Close stmt 
2016-04-14T04:54:04.780113Z 181 Prepare select * from `questions` where `questions`.`category_id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 
2016-04-14T04:54:04.780301Z 181 Execute select * from `questions` where `questions`.`category_id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20') 

そして、::

2016-04-14T04:54:28.762529Z 182 Prepare select * from `categories` 
2016-04-14T04:54:28.762663Z 182 Execute select * from `categories` 
2016-04-14T04:54:28.762997Z 182 Close stmt 
2016-04-14T04:54:28.765550Z 182 Prepare select `id` from `questions` where `questions`.`category_id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 
2016-04-14T04:54:28.765708Z 182 Execute select `id` from `questions` where `questions`.`category_id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20') 

これらの絶滅は、ところで、dd($categories);は与え

$categories = Category::with(['questions'])->get();

は私を与えます同じデータ構造ですが、空の質問集があります

答えて

1

ああ、クエリロガーが助けました...

selectでネストされた$クエリを使用するには、使用しているフィールドをjoinに含める必要があります。この場合、SQLはcategory_idに参加しています。

だから、次のようになります。

$categories = Category::with(['questions'=>function($query){ 
     $query->select('id', 'category_id'); 
    }])->get(); 

は(しかしきちんとした配列に質問IDを収集するためにクールになる)私を取得します:

ところで

enter image description here

+0

、配列もOK渡します: '$ query-> select(['id'、 'category_id']);' – ThangTD

関連する問題