Laravel技术问询:如何获取登录用户插入的全部数据库数据?
问题:如何获取数据库表中已登录用户插入的所有行?
我现在遇到的问题是:用first()方法只能获取用户插入的最后一行数据,换成get()方法又会报错「Property [honors] does not exist on this collection instance.」。比如app_id为2708的用户插入了3行数据,我要怎么获取该用户关联的所有数据?
以下是我的代码片段:
Controller.php 文件
public function index(){ $data['user1'] = UserModel::where('seq_id','=',Session::get('loginId'))->first(); return view ("enrollment-steps.step2", $data, [ 'data'=>$data['user1'], ]); }
Blade.php 文件
<label><strong> Honors if any(Secondary level): </strong></label> <div class="col-sm-12 col-lg-4"> <div class="form-group row"> <label for="step2_honor" class="col-sm-3 text-right control-label col-form-label">Honors</label> <div class="col-sm-9"> <input class="form-control" type="text" id='step2_honor' placeholder="Secondary" value="{!! $user1->honors !!}" > </div> </div> </div>
解决方案
1. 控制器中获取用户的所有数据行
把first()替换为get(),这样就能拿到该用户对应的所有数据集合:
public function index(){ // get() 返回包含多个UserModel实例的集合 $data['userRecords'] = UserModel::where('seq_id','=',Session::get('loginId'))->get(); return view ("enrollment-steps.step2", $data); }
2. 视图中遍历集合显示所有数据
get()返回的是模型集合,不是单个模型实例,不能直接通过->honors访问属性,必须循环遍历每一条记录:
<label><strong> Honors if any(Secondary level): </strong></label> <div class="col-sm-12 col-lg-4"> @foreach($userRecords as $record) <div class="form-group row"> <label for="step2_honor_{{ $record->id }}" class="col-sm-3 text-right control-label col-form-label">Honors</label> <div class="col-sm-9"> <input class="form-control" type="text" id='step2_honor_{{ $record->id }}' placeholder="Secondary" value="{!! $record->honors !!}" > </div> </div> @endforeach </div>
关键说明
first():仅返回匹配条件的单条模型实例,所以只能拿到单行数据。get():返回匹配条件的所有模型实例组成的集合,必须通过循环遍历才能访问每个实例的属性,直接访问集合的honors属性会报错(集合本身没有该属性)。- 给每个input的id加上
$record->id是为了避免DOM元素id重复,保证页面逻辑正确。
内容的提问来源于stack exchange,提问作者CaptainCRAZY
相关产品推荐
相关产品推荐

