【问题标题】:Laravel/Eloquent best way to do related searchLaravel/Eloquent 进行相关搜索的最佳方式
【发布时间】:2017-05-28 19:32:45
【问题描述】:

当您想查询与模型相关的模型关系时,在 Laravel/Eloquent 中进行相关查询的最佳/正确方法是什么?

例如:

书籍有很多印刷品 印刷品有出版商

我想查找指定出版商的所有图书

Books:where('printings.publishers', '=', $id);

关于如何设置的任何建议?

谢谢


更新:

难道不能在模型中进行设置,使用 hasMany/ManyThrough 来创建“魔法”吸气剂吗?

模型是这样的

书籍

  • 身份证
  • 标题

打印

  • 身份证
  • book_id
  • publisher_id
  • author_id

出版商

  • 身份证
  • 姓名

作者

  • 身份证
  • 姓名

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    首先建立正确的关系。 Book 有很多 PrintingPrinting 属于 Publisher

    Book::whereHas('printings', function($q) use($id) {
        $q->where('publisher_id', $id);
    })->get();
    

    【讨论】:

      【解决方案2】:

      这就是你通常的做法:

      Books::with(['printings' => function ($q) use ($id) {
          // Query on the relationship
          $q->where('publishers', $id);
      }])->get();
      

      编辑:

      我误解了这个问题。正如@AlexeyMezenin 回答的那样,您正在寻找的是->whereHas

      Books::whereHas('printings', function ($q) use ($id) {
          // Query on the relationship
          $q->where('publishers', $id);
      })->get();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-12
        • 2010-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-10
        • 1970-01-01
        相关资源
        最近更新 更多