【问题标题】:How to search in another table in Laravel with Eloquent?如何使用 Eloquent 在 Laravel 的另一个表中搜索?
【发布时间】:2021-08-07 06:22:24
【问题描述】:

我有两个模型:

Order
Customer

我在orders 表中有customer_idcustomerstable 中的客户详细信息(姓名、电话、电子邮件等)。但我正在为订单表编写查询。

现在,我想在 Orders 上使用 Customer Name 进行搜索,但在 Orders 表中我只有 customer_id

我将如何链接客户表,以便我可以使用客户名称进行搜索。我想用 Eloquent 做到这一点。

这怎么可能?

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    使用 Eloquent 进行关系过滤有多种方法。

    您可以使用whereHas 或使用高级联接/左联接查询来实现它。

    我建议你研究一下 Laravel 文档上的 Eloquent 过滤,你的任务所需的一切都应该在那里。

    https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

    https://laravel.com/docs/8.x/queries#advanced-join-clauses

    【讨论】:

      【解决方案2】:

      在模型中定义关系

      客户模型

      public function orders()
      {
         return $this->hasMany(Orders::class);
      }
      

      订单型号

      public function customer()
      {
         return $this->belongsTo(ustomer::class, 'foreign Key', 'id');
      }
      

      然后你可以调用关系并搜索你想要的 Customer::whereHas('orders')

      【讨论】:

        猜你喜欢
        • 2020-06-06
        • 1970-01-01
        • 1970-01-01
        • 2017-11-23
        • 2019-03-31
        • 2016-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多