SQL选择行并分组为数组项

时间:2018-08-16 09:30:00

标签: mysql sql laravel

我的项目包含由一位或多位作者撰写的书籍(产品)。

以下数据库表可用:

  • 表“产品”;列“ id”,“标题”等
  • 表“作者”;列“ id”,“名称”,“电子邮件”等。
  • 关系表“ products_auhtors”;列“ id”,“ product_id”,“ author_id”

现在,我要查询所有产品,并且结果也应包括相关作者。

$products = $this->db( 'products' )
        ->join( 'products_authors', 'products.id', '=', 'products_authors.product_id' )
        ->join( 'authors', 'authors.id', '=', 'products_authors.author_id' )
        ->select(
            'products.*',
            'authors.*'
        )
        ->get();

问题:我想将所有作者(由于一个产品可以有1个以上的事实)分组为数组。

所以实际上结果应该像这样:

[
    {
        id: 1,
        title: "title of the book"
        authors: [
            {
                id: 11,
                name: "name of author 1",
                email: "author1@email.com"
            },
            {
                id: 22,
                name: "name of author 2",
                email: "author2@email.com"
            }
        ]
    },
    {
        id: 2,
        title: "title of the book2"
        authors: [
            {
                id: 11,
                name: "name of author 1",
                email: "author1@email.com"
            },
            {
                id: 22,
                name: "name of author 2",
                email: "author2@email.com"
            }
        ]
    }
]

我正在使用Laravel's query builder,但是我当然也可以使用原始SQL。

有什么提示可以使我更加接近目标吗?

2 个答案:

答案 0 :(得分:0)

我建议它不是基于原始数据库关系,而是基于模型。

您应该有类似的内容:

public function authors()
{
    return $this->hasMany('App\Namespace\Author');
}

然后只需使用

$products = Products::with('authors')->get();

还请注意,当您执行->select('products.*','authors.*')之类的选择时,您的product.id将被authors.id覆盖,因为它将映射到结果['id']键-这是常见的Laravel中的查询错误。

答案 1 :(得分:0)

这可以解决问题:

return $this->belongsToMany('App\Models\AuthorsModel', 'products_authors',
            'product_id', 'author_id');