我正在学习使用Laravel的MVC模式,而Eloquent 的模型对我来说是一种压倒性的感觉.Eloquent 模型返回表的列的集合,但我希望另一个表的集合成为该模型的属性.

我有三张桌子

Books

id,
title

Contribution

book_id,
contributor_id,
role

Author

id,
name

我想要更改函数的返回值,如Model Books的all()、find()、get()等,以包括贡献者

从这一点开始:

[  "id" => "1", 
   "title" => "CS101" 
]

对此:

[ "id" => "1",
  "title" => "CS101",
  "contributors" => [
   [
    "id" => "1",
    "name" => "Einstein"
    "role" => "author"
   ],
   [
    "id" => "2",
    "name" => "Thomas"
    "role" => "translator"
   ]
  ]
]

我是不是应该使用Eloquent 并构建自己的模型,或者是否有可以覆盖的Eloquent 函数或更好的方法来实现这一点

推荐答案

首先,您需要创建Book::classAuthor::class之间的关系

Book.php

namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
 
class User extends Model
{
    /**
     * The Author that belong to the book.
     */
    public function contributors(): BelongsToMany
    {
        return $this->belongsToMany(Author::class, 'contribution', 'book_id', 'contributor_id')->withPivot('role');
    }
}

然后,您可以在运行查询时加载关系

$books = Book::with('contributors')->get();

$book = Book::with('contributors')->first();

这将导致 struct

[
  "id" => "1",
  "title" => "CS101",
  "contributors" => [
    [
      "id" => "1",
      "name" => "Einstein",
      "pivot" => [
        "role" => "Author",
      ]
    ],
    [
      "id" => "2",
      "name" => "Thomas"
      "pivot" => [
        "role" => "Translator",
      ]
    ]
  ]
]

最有趣的是,通过这种方式,关系将被Eager 加载,这意味着将只运行两个查询来获得结果.

Php相关问答推荐

在不刷新页面的情况下无法使用JQuery更新id

基于验证动态更改输入字段类(名称密码)&

尽管包含目标日期,但日期范围比较仍有意外输出

向在添加到购物车上动态创建的WooCommerce产品添加发货类别

PHP日期操作,将多个日期输出为格式化字符串

闭包绑定$This和垃圾收集器

用于计算付款费用的WooCommerce管理编辑产品中的自定义复选框

是否重新排序多维数组元素以将所有子数组中的子数组移动到元素列表的底部?

Apache只允许index.php-不从根目录工作

PHP根据特定索引值从中删除子数组

PHP -将字符串拆分为两个相等的部分,但第二个字符串中的单词更多

在php中,方法之间的属性链接是如何工作的

在带有livewire 3的laravel中使用规则方法时,无法进行实时验证

向WooCommerce管理订单总额添加自定义总额行

在 WooCommerce 更新结帐事件上动态更新自定义内容

如何限制 woocommerce 中相关产品的标题长度

在特征中使用类的属性

我需要一个正则表达式模式来获取在不包含特定字符串后面的模式中的文本

如何在自定义消息中包含 WooCommerce 选定的产品变体详细信息

无法在 Laravel 10 中安装 jenssegers/mongodb