Mysql SQL选择行和组作为数组项
我的项目包含由一个或多个作者编写的一系列书籍(产品) 以下数据库表可用:Mysql SQL选择行和组作为数组项,mysql,sql,laravel,Mysql,Sql,Laravel,我的项目包含由一个或多个作者编写的一系列书籍(产品) 以下数据库表可用: 表“产品”;列“id”、“标题”等 表“作者”;“id”、“姓名”、“电子邮件”等列 关系表“产品”;“id”、“产品id”、“作者id”列 现在我想查询所有产品,结果也应该包括相关作者 $products = $this->db( 'products' ) ->join( 'products_authors', 'products.id', '=', 'products_authors.p
- 表“产品”;列“id”、“标题”等
- 表“作者”;“id”、“姓名”、“电子邮件”等列
- 关系表“产品”;“id”、“产品id”、“作者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();
问题:我希望将所有作者(由于一个产品可以有多个作者)分组为数组
所以事实上结果应该是这样的:
[
{
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"
}
]
}
]
我正在使用,但当然我也可以使用原始SQL
有什么建议可以让我更接近我的目标吗?我建议不要基于原始数据库关系,而是基于模型 您应该有如下内容:
public function authors()
{
return $this->hasMany('App\Namespace\Author');
}
然后简单地使用
$products = Products::with('authors')->get();
还请注意,当您执行类似于
->select('products.*','authors.*')
的选择时,您的products.id将被authors.id覆盖,因为它将映射到results['id']键-这是Laravel中查询的常见错误。这起到了以下作用:
return $this->belongsToMany('App\Models\AuthorsModel', 'products_authors',
'product_id', 'author_id');
您是否也安装了laravel模型?如果是这样的话,可以使用关系来代替手动查询。不,我没有使用模型幸运的是,这并不能回答我的问题,因为我使用的是一个包含产品id和作者id的透视表。如您所建议的,使用“hasMany”,将在“authors”表中进行搜索,这是没有帮助的。