laravel - 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
列,我想从关系中获取用户。
解决方案
当使用这样的集合时;
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 = ?
- ... 等等
推荐阅读
- c# - 如果没有线程回调异步函数怎么办
- javascript - 在服务角度测试异步函数:在茉莉花指定的超时内未调用异步回调
- prometheus - 如何使用 JAVA Prometheus Pushgateway 客户端推送具有多个标签(键值)的无类型指标?
- spring - sslContext 中的 loadTrustMaterial 是什么?| 双向 TLS
- json - 存储:数据库 vs 内存对象 vs 内存数据库
- android - 如何在 Espresso 中测试 Android 通知
- ios - 错误 - 链接器命令失败,退出代码为 1
- javascript - asNavFor 在 Angular 8 中不工作 ngx-slick-carousel
- ruby-on-rails - 在 CSV 上传时添加项目
- .net - 在不知道变量名称的情况下从 List 获取值