php - 未定义的属性:stdClass::$id 用于 laravel API
问题描述
我在 laravel 上使用 API 的查询生成器执行此操作
$shipments = DB::table('shipment_batches')
->select(
"shipments.id as shipment_id",
"shipments.fulfillment_id",
"shipments.shipped_address_id",
"shipments.courrier_id",
"shipments.status",
"shipments.is_intro",
"shipments.is_express",
"shipments.shipment_batch_id",
"shipments.intro_shipment_date",
"shipments.intro_shipped_at",
"shipments.tracking_number",
"shipments.is_gift",
"shipments.ship_unit",
"shipments.shipment_notes",
"shipments.is_one_time_product",
"shipments.one_time_product_shipment_date",
"shipments.one_time_product_shipped_at",
"shipments.shipment_options",
"shipments.is_migrated",
"shipments.migration_has_error",
"shipments.in_process_date",
"shipments.shipment_date_at",
"shipments.link",
)
->join('shipments', 'shipments.shipment_batch_id', '=', 'shipment_batches.id')
->join('fulfillments', 'fulfillments.id', '=', 'shipments.fulfillment_id')
->join('subscriptions', 'subscriptions.id', '=', 'fulfillments.subscription_id')
->whereMonth('shipment_batches.shipment_date', '>', date('m'))
->whereYear('shipment_batches.shipment_date', '=', date('Y'))
->where('subscriptions.user_id', $id)
->orderBy('shipment_batches.id', 'ASC')
->get();
return UpcomingShipmentsResource::collection($shipments);
我有这个资源集合
class UpcomingShipmentsResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
"id" => $this->id,
"hashed_id" => hashids_encode($this->id),
"padded_id" => id_padder($this->id),
];
}
}
我刚刚删除了其他数组返回值以简化集合。并在 API 上作为 json 返回之前添加hashed_id
并padded_id
修改结果
我收到了这个错误
未定义的属性:stdClass::$id
是否可以从查询生成器中创建集合?如何?
解决方案
在查询中选择:
->select(
"shipments.id as shipment_id",
"shipments.fulfillment_id",
"shipments.shipped_address_id",
"shipments.courrier_id",
"shipments.status",
"shipments.is_intro",
"shipments.is_express",
"shipments.shipment_batch_id",
"shipments.intro_shipment_date",
"shipments.intro_shipped_at",
"shipments.tracking_number",
"shipments.is_gift",
"shipments.ship_unit",
"shipments.shipment_notes",
"shipments.is_one_time_product",
"shipments.one_time_product_shipment_date",
"shipments.one_time_product_shipped_at",
"shipments.shipment_options",
"shipments.is_migrated",
"shipments.migration_has_error",
"shipments.in_process_date",
"shipments.shipment_date_at",
"shipments.link",
)
您没有选择“id”,因此在 toArray() 方法中不会有“$this->id”。
您应该添加:
->select(
"tablename.id as id",
...
)
推荐阅读
- kubernetes - Kubernetes Pod 的 csshX 替代方案是什么?
- java - 如何使用spring cacheble在Hazelcast缓存地图上设置TTL
- react-native - 可能的未处理承诺拒绝(id:0):错误:不支持的输入文件类型
- javascript - 如何在本机反应中使用 Animated ScrollView 为这样的项目设置动画?
- unit-testing - Mockito - Kotlin 模拟一个给定字符串的接口返回一个字符串
- javascript - 如何在自定义 amp 脚本中使用 jquery?
- node.js - DialogFlow:检索 JSON,如何筛选它?
- slurm - Slurm - 随机分配 GPU
- c# - 在没有线程锁定的情况下通过同步 c# 调用异步
- flutter - Flutter Web - 在不同页面的浏览器搜索栏中显示不同的浏览器链接,而不是一个链接