选择“with”中的语句返回空数组

时间:2016-04-14 04:20:52

标签: php mysql laravel laravel-5

我正在尝试使用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);给出了相同的数据结构,但其中一个有空的问题集合

1 个答案:

答案 0 :(得分:1)

啊,查询记录器有帮助......

要将嵌套的$查询与select一起使用,您需要将其正在使用的字段包含在join中。在这种情况下,SQL正在加入category_id

所以看起来应该是这样的:

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

获取我(虽然将问题ID收集到一个整齐的数组中会很酷):

enter image description here