LARAVEL框架和雄辩的ORM模型

时间:2018-12-20 15:35:51

标签: laravel orm eloquent

{ "_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 }

上面是“书籍”表

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

{ "author" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "author" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }

我正在学习Laravel。

2 个答案:

答案 0 :(得分:0)

您可以使用GROUP_CONCAT

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" ] }

答案 1 :(得分:0)

如果表结构在您的控制之内,那么更好的解决方案是将数据放入两个表booksauthors中,以避免像现在单个表那样重复数据

然后定义两个Eloquent Models并建立一对多关系。与一个作者一样,作者可以编写许多书。

所以Book模型可能看起来像这样:

class Book extends Model
{
    public function author()
    {
        return $this->belongsTo(Author::class);
    }
}

Author模型可能看起来像这样:

class Author extends Model
{
    public function books()
    {
        return $this->hasMany(Book::class);
    }
}

现在,您可以使用relationshipeager loading和少量collection processing以您喜欢的格式获取数据:

$authors = Author::with('books')->get()->map(function ($author) {
    return [
        'author' => $author->name,
        'books'  => $author->books->pluck('title')
    ];
});

您可能还想阅读Database Normalization,尤其是The 1st Normal Form