LARAVEL框架和雄辩的ORM模型

LARAVEL框架和雄辩的ORM模型,laravel,orm,eloquent,Laravel,Orm,Eloquent,上面是一张“书”桌 使用LARAVEL框架和雄辩的ORM模型,如何返回以下结果: { "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 } { "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 } { "_id" : 8645, "title" : "Eclogues", "author" : "Dante

上面是一张“书”桌

使用LARAVEL框架和雄辩的ORM模型,如何返回以下结果:

{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 }
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
我在学拉威尔。

你可以用

这将使您:

Book::groupBy('author')
    ->select(DB::raw('GROUP_CONCAT(title) as books'), 'author')
    ->get()
    ->map(function ($author) {
        $author->books = preg_split('/,/', $author->books);
        return $author;
    });

如果表结构在您的控制范围内,那么更好的解决方案是将数据放在两个表中
图书
作者
,以避免数据重复,就像现在使用单个表时一样

然后定义两个并建立一对多关系。正如在中一样,一个作者可以写许多书

因此,
Book
模型可能如下所示:

类目扩展模型
{
公共功能作者()
{
返回$this->belongsTo(Author::class);
}
}
作者
模型可能如下所示:

类作者扩展模型
{
公共职能书()
{
返回$this->hasMany(Book::class);
}
}
现在,您可以使用和以您喜欢的格式获取数据:

$authors=Author::with('books')->get()->map(函数($Author){
返回[
'author'=>$author->name,
'books'=>$author->books->pull('title')
];
});

您可能还想仔细阅读,就您的情况而言,更具体地说。

到目前为止您尝试了什么?您似乎在寻找一对多的关系?如果是这样:我需要滑动books表吗?我需要得到完全相同的输出,就像我说的,你只需要添加一个拆分器,然后。。。我已经更新了我的答案以匹配您的输出。
Book::groupBy('author')
    ->select(DB::raw('GROUP_CONCAT(title) as books'), 'author')
    ->get()
    ->map(function ($author) {
        $author->books = preg_split('/,/', $author->books);
        return $author;
    });
{ "author" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "author" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }