2016-04-14 11 views
1

我試圖使用Laravel 5.1從with關係中返回單個列。我想要獲取所有類別,每個類別都有一組相關的問題ID(而不是完整的問題對象)。在「with」中選擇語句返回空數組

$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'); 
} 

同樣,我使用mysql query logger登錄實際的SQL。

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

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') 

而且,嵌套$query一個告訴我,我選擇ID,符合市場預期:

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);給相同的數據結構,但其中一個具有空集合的問題

回答

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