【问题标题】:Select statement in "with" returning empty arrays“with”中的选择语句返回空数组
【发布时间】:2016-08-05 11:02:16
【问题描述】:

我正在尝试使用 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); 将这些都淘汰了,给出了相同的数据结构,但一个问题的集合是空的

【问题讨论】:

    标签: php mysql laravel laravel-5


    【解决方案1】:

    啊,查询记录器帮了忙……

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

    所以它应该是这样的:

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

    让我明白(不过,将问题 ID 收集到一个整洁的数组中会很酷):

    【讨论】:

    • 顺便说一句,传递数组也可以:$query->select(['id', 'category_id']);
    猜你喜欢
    • 2012-12-12
    • 2015-03-17
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多