【问题标题】:Specific columns using eloquent in a nested eager loading在嵌套急切加载中使用 eloquent 的特定列
【发布时间】:2021-10-02 08:33:03
【问题描述】:

有没有办法只限制在 Laravel 的嵌套预加载中可以选择的列数

目前,我有 3 个相互关联的模型。例如,假设我们有 Publisher 模型、Authors 模型和 books 模型

出版商与作者有关​​系,而作者与书籍的模型有关系。

Publisher 模型具有如下列:

  • 身份证
  • 姓名
  • 地址
  • 传真号码
  • 电子邮件地址

作者的模型包含:

  • 身份证
  • 姓名
  • 地址
  • 电子邮件
  • 出版书籍
  • publishers_id

书籍模型包含:

  • 身份证
  • 标题
  • authors_id
  • published_on
  • 类别

如果我想查看某个出版公司已出版的书籍:这就是我提取记录的方式

$published_books::Publisher::with('authors.books')->take(1);

有了这个,我得到这样的回应:

"id" : 1,
"name" : "Longhorn Ke",
"address" : "14th Street",
"fax number" : "null",
"email_address" : "longhorn@mail.com",
"author" :{
 "id" : 4,
 "name" : patel,
 "email" : patelguru@mail.com,
 "published_books" : 12,
 "publishers_id" : 1,
 "books" : {
  "id": 1,
  "title" : "Art of life",
  "authors_id" : 1,
  "published_on" : "2020-07-12 14:22:25",
  "category" : "Life teachings",
 }

}

 

我想要的是,当我通过关系加载一本书时,我只想获取出版商名称,作者姓名和书籍详细信息,如下所示:

"id" : 1,
"name" : "Longhorn Ke",
"author" :{
     "id" : 4,
     "name" : patel,
     "books" : {
         "id": 1,
          "title" : "Art of life",
          "authors_id" : 1,
          "published_on" : "2020-07-12 14:22:25",
          "category" : "Life teachings",
 }

}

如何使用 eloquent 实现这一目标?在这一点上,我了解 eloquent 允许在嵌套加载时选择特定列,如此链接 https://laravel.com/docs/master/eloquent-relationships#eager-loading-specific-columns 所示,但我如何在所有模型中执行此操作以实现上面显示的代码结果

【问题讨论】:

    标签: php laravel eloquent eloquent-relationship


    【解决方案1】:

    对于最顶级的模型,您需要select();对于您需要的关系relationship:id,...

    $published_books = Publisher::with(['authors.books', 'authors:id,name'])
        ->select('id', 'name')
        ->take(1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-30
      • 2021-01-21
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      相关资源
      最近更新 更多