Laravel: 如何从查询生成器对象中获取值
Laravel: how to get value from query builder object
我是 laravel 的新人。我有一个 table 但没有这方面的模型。我在下面使用来获取记录。
$classes = DB::table('school_classes')->get();
return view('classes', ['allClass' => $classes]);
下面returns:
[{"id":1,"register_school_id":1,"class":"I","section":"A","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":2,"register_school_id":1,"class":"I","section":"B","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":3,"register_school_id":1,"class":"I","section":"C","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"}, {"id":4,"register_school_id":1,"class":"I","section":"D","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":5,"register_school_id":1,"class":"I","section":"E","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"}]
我如何才能分别选择每个项目的值...我尝试了 foreach 但出现错误。
请帮助。提前致谢。
查询生成器 returns 一个 Illuminate\Support\Collection
实例。您可以通过以下方式访问该集合:
@foreach($allClass as $class)
{{ $class->id }}
@endforeach
同时勾选 Collections
您想获取数组格式的数据,那么您可以使用“toArray”,也可以使用 foreach 循环 Laravel 函数轻松访问数据。
$classes = DB::table('school_classes')->get()->toArray();
return view('classes', ['allClass' => $classes]);
我是 laravel 的新人。我有一个 table 但没有这方面的模型。我在下面使用来获取记录。
$classes = DB::table('school_classes')->get();
return view('classes', ['allClass' => $classes]);
下面returns:
[{"id":1,"register_school_id":1,"class":"I","section":"A","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":2,"register_school_id":1,"class":"I","section":"B","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":3,"register_school_id":1,"class":"I","section":"C","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"}, {"id":4,"register_school_id":1,"class":"I","section":"D","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"},
{"id":5,"register_school_id":1,"class":"I","section":"E","created_at":"2020-03-19 00:00:00","updated_at":"2020-03-19 00:00:00"}]
我如何才能分别选择每个项目的值...我尝试了 foreach 但出现错误。 请帮助。提前致谢。
查询生成器 returns 一个 Illuminate\Support\Collection
实例。您可以通过以下方式访问该集合:
@foreach($allClass as $class)
{{ $class->id }}
@endforeach
同时勾选 Collections
您想获取数组格式的数据,那么您可以使用“toArray”,也可以使用 foreach 循环 Laravel 函数轻松访问数据。
$classes = DB::table('school_classes')->get()->toArray();
return view('classes', ['allClass' => $classes]);