首页 > 解决方案 > Laravel:此集合实例上不存在属性 [用户]

问题描述

在 Laravel 中,我有 Orders 模型,其中每个订单只属于一个用户,

我想在获取订单时只返回用户名和订单 ID,所以在我的 OrdersController 中有这个函数

public function getAllOrders()
    {
        $orders = Order::all();
        return new OrderResource($orders);
    }

在我的 OrderResource 我有

public function toArray($request)
    {
        return [
            'user' => $this->user,
            'id' => $this->id,
        ];
    }

我收到一个错误消息 Property [user] does not exist on this collection instance

我认为原因在于它$orders是一个集合,我应该遍历它并为每个订单获取与之关联的用户,但我不知道该怎么做。

注意:我在用户和订单模型上使用 oneToMany 和 belongsTo。所以订单表没有user列,我想从关系中获取用户。

标签: laravel

解决方案


当使用这样的集合时;

public function getAllOrders()
{
    return OrderResource::collection(Order::all());
}

当使用这样的模型时;

public function getOrder($id)
{
    return new OrderResource(Order::find($id));
}

文档中的更多信息:https ://laravel.com/docs/7.x/eloquent-resources#concept-overview


注意:为避免N+1查询,您应该这样获取订单;Order::with('user')->get();代替Order::all()

不同之处在于Order::with('user')->get();它将执行两个查询。

  • select * from orders
  • select * from users where id in (?, ?, ?, ?, ...)

Order::all()将执行 N+1 个查询(N = 订单数)

  • select * from orders
  • select * from users where id = ?
  • select * from users where id = ?
  • select * from users where id = ?
  • ... 等等

推荐阅读