【发布时间】:2019-11-01 16:36:25
【问题描述】:
我有 2 个表 users 和 data 。
在用户表中有:
标识 |姓名 |电子邮件 |等等
在数据表中有:
标识 |用户 ID |无数据 |等等
我像这样创建模型数据
public function users()
{
return $this->HasMany(\App\User::class ,'id');
}
我的控制器:
public function pns()
{
$data = Data::get();
//DB::table('data')
//->join('users','data.user_id','=','users.id')
//->where(['user' => 'something', 'otherThing' =>
// 'otherThing'])
//->get(); // i trying to join this table but still error
return view('admin.data',['data' => $data]);
}
现在我想在表格中显示视图数据:
在我的视图刀片上:
<th>No </th>
<th>id </th>
<th>Name </th>
<th>email </th>
@php
$no=0;
@endphp
@foreach ($data as $i)
<tr>
<td class=" ">{{ ++$no }}</td>
<td class=" ">{{ $i->user_id}}</td>
<td class=" ">{{ $i->users->name}}</td>
<td class=" ">{{ $i->email}}</td>
</tr>
这个user_id被显示了,但是这个'name'不能显示并且得到错误:
此集合实例上不存在属性 [名称]。
编辑了我的 dd($data)
#attributes: array:18 [▼
"id" => 1
"user_id" => 6
"email" => 'q@gmail.com'
//etc
"created_at" => "2019-06-18 17:27:54"
"updated_at" => "2019-06-18 17:27:54"
]
【问题讨论】:
-
你可以给你想要的字段起别名,也可以使用 Eloquent 关系来简化它stackoverflow.com/a/56656399/7498116
标签: laravel