Php 选择“中的语句”;加上;返回空数组
我试图使用Laravel5.1从具有关系的Php 选择“中的语句”;加上;返回空数组,php,mysql,laravel,laravel-5,Php,Mysql,Laravel,Laravel 5,我试图使用Laravel5.1从具有关系的返回一个列。我想得到所有类别,每个类别都有一个相关问题ID数组(不是完整的问题对象) $categories=Category::with(['questions'])->get()获取包含问题对象数组的所有类别。这不是我想要的。我只想要问题ID 下面,我添加了一个要选择的嵌套查询: $categories = Category::with(['questions'=>function($query){ $query->
返回一个列。我想得到所有类别,每个类别都有一个相关问题ID数组(不是完整的问题对象)
$categories=Category::with(['questions'])->get()代码>获取包含问题对象数组的所有类别。这不是我想要的。我只想要问题ID
下面,我添加了一个要选择的嵌套查询:
$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查询记录器来记录实际的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
one告诉我正在选择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)
提供了相同的数据结构,但其中一个问题的集合是空的啊,查询记录器帮助
要将嵌套的$query与选择一起使用
,您需要包括它用于连接的字段。在本例中,SQL是在category\u id
上加入的
所以它应该看起来像:
$categories = Category::with(['questions'=>function($query){
$query->select('id', 'category_id');
}])->get();
了解我(将问题ID收集到一个整洁的数组中会很酷):
顺便说一句,传递数组也可以:$query->select(['id','category\u id'])代码>