Laravel 9关系不返回数据数组
Laravel 9关系不返回数据数组
我正在尝试构建一个查询,从具有一对多关系的两个表中获取数据。但是,输出的dd($customer);结果并不是关系的数组数据,而是:
0 => App\Models\Customer {#1496 ▼ #connection: "mysql" #table: "customers" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] +preventsLazyLoading: false #perPage: 15 +exists: true +wasRecentlyCreated: false #escapeWhenCastingToString: false #attributes: array:42 [] #original: array:42 [] #changes: [] #casts: array:1 [] #classCastCache: [] #attributeCastCache: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: array:1 [▼ "xray_machine" => Illuminate\Database\Eloquent\Collection {#1538 …2} ] #touches: [] +timestamps: true #hidden: [] #visible: [] #fillable: array:34 [] #guarded: array:1 [] #forceDeleting: false }
Customer模型
public function xray_machine() { return $this->hasMany(Xray_machine::class); }
Xray_machine
模型
public function customer() { return $this->belongsTo(Customer::class); }
控制器
public function epes_scheduled(){ $customers = Customer::with('Xray_machine')->get(); dd($customers); return view('work_orders/epe_scheduled', compact('customers')); }
并且在视图中(在控制器中删除dd()后),我得到以下错误:
该集合实例上不存在属性[model]。
视图:
@foreach ($customers as $customer)@endforeach @if($customer->customer_name) {{$customer->customer_name}} @endif @if($customer->Xray_machine->model) {{$customer->Xray_machine->model}} @endif
Laravel 9关系不返回数据数组的原因是因为Laravel返回的是数据的集合(Collection),而不是数组。如果需要数组,可以使用toArray()
方法将数据转换为数组。
解决方法是在查询关系时使用toArray()
方法将集合转换为数组。例如:
$customers = Customer::with('Xray_machine')->get()->toArray(); dd($customers);
这样就可以得到一个包含数据数组的集合。
为什么要这样做呢?
我同意你的评论,但是这里的“为什么”不重要提问者问的是为什么不返回一个数组,而这个答案虽然有点泛泛,但确实解释了返回的是一个集合,如果你想要一个数组,可以使用->toArray()
。并不是有很多情况下你想要(或需要)这样做,但这个答案在技术上是“正确”的。