2 回答
TA贡献1830条经验 获得超9个赞
首先,最好id从关系定义中删除或声明right foreign key:
class Job extends Model
{
//this
public function pcns(){return $this->hasMany('App\Pcn');}
//or this
public function pcns(){return $this->hasMany('App\Pcn', 'job_id', 'id');}
}
class Department extends Model
{
//this
public function pcns(){return $this->hasMany('App\Pcn');}
//or this
public function pcns(){return $this->hasMany('App\Pcn', 'department_id', 'id');}
}
第二步:最好预先加载关系以减少所需的查询数量:
public function index()
{
$pcns = Pcn::with(['job', 'department'])->paginate(50);
return view('pcn.index', compact('pcns'));
}
之后,在你看来,你并不真正需要$key=>$value的@foreach:
@foreach($pcns as $pcn)
<td>{{ $pcn->control_number }}</td>
<td>{{ $pcn->job->name }}</td>
<td>{{ $pcn->department->name }}</td>
@endforeach
TA贡献1909条经验 获得超7个赞
paginate()方法不返回的集合Pcn,它返回一个LengthAwarePaginator,当变成一个数组时,它有作为索引 ( total, per_page, next_link....)
您需要从 LengthAwarePaginator
@foreach($pcns as $pcn)
<td>{{ $pcn->control_number }}</td>
<td>{{ $pcn->job->name }}</td>
<td>{{ $pcn->department->name }}</td>
@endforeach
顺便说一下,您应该在查询中预加载job和department关系以仅向数据库发送3 个请求而不是101。
$pcns = Pcn::with(['job', 'department'])->paginate(50);
- 2 回答
- 0 关注
- 171 浏览
添加回答
举报