我正在尝试使用Laravel 5.1从with
关系返回单个列。我想得到所有类别,每个类别都有一系列相关的问题ID(不是完整的问题对象)。
$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);
给出了相同的数据结构,但其中一个有空的问题集合