【问题标题】:How can I link 2 existing models in my laravel code?如何在我的 laravel 代码中链接 2 个现有模型?
【发布时间】:2020-02-25 08:37:06
【问题描述】:

我有两种型号的客户和订单。他们已经分别感染了

$customers = customer::all();

$orders = orders::all();

customerID=1 有 orderID : 1, 2,4 customerID=2 有 orderID : 3,5,9

它们是相关的(hasMany,belongsTo),但由于某种原因,它们是分开的,但我想将它们作为 API 中的响应发送,使用 toJson 或 ToArray 作为将订单嵌套给正确客户的一个数据。

我怎样才能实现该链接以在最后有一个变量 $customersWithOrders 应该转换为 JSON ?

我使用的是 laravel 5.5

【问题讨论】:

  • 不要单独获取它们...使用关系; Customer 应该有多个 Order 记录,并且您应该有一个关系来反映这一点。然后,你可以做$customers = Customer::with('orders')->get();(注意:模型是TitleCase和单数:CustomerOrder,而不是customerorders

标签: laravel


【解决方案1】:

我不知道上下文是什么。将关系定义为提到的其他答案是一个很好的解决方案。

另外,我最近阅读了一篇关于这个特定场景的pretty good article

因此,如果您已经检索到客户和订单,您也可以这样做:

$customers = Customer::all();
$orders = Order::all();

return $customers->each(function ($customers) use ($orders) {
    $customer->setRelation('orders', $orders->where('customer_id', $customer->id));
});

【讨论】:

  • 谢谢,我会测试一下,我希望 $orders->where('customer_id',$customer->id) 确实调用数据库。我希望一切都用内存中的数据完成。我读了他的一篇文章,他真的把我们的注意力吸引到我们有时会忽略的非常重要的事情上:reinink.ca/articles/…
  • 肯定不会再访问数据库了。
【解决方案2】:

如果你已经有一个关系,你只需使用它。例如在模型Customer.php

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

然后您可以致电$customer->orders获得客户订单

【讨论】:

    【解决方案3】:

    如果您已经定义了关系,您可以简单地通过预先加载来获取数据

    // in customer model
    public function orders()
    {
        return $this->hasMany(orders::class, 'orderID');
    }
    
    // in controller
    $customersWithOrders = customer::with('orders')->get();
    return response()->json(['customersWithOrders' => $customersWithOrders]);
    
    // in js
    for (let customer in response.customersWithOrders){
        let orders = customer.orders
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2022-01-25
      • 2016-03-06
      • 2019-09-02
      • 2022-09-29
      相关资源
      最近更新 更多