关于在 Laravel 中检索一对多关系数据,我有一些奇怪的问题。
模型
// JobTypes model
public function jobs()
{
// one type of job has many jobs
return $this->hasMany('App\Jobs', 'id'); // id refer to jobs.id
}
// Jobs model
public function job_types()
{
// one job only belongs to one type of job
return $this->belongsTo('App\jobTypes');
}
数据透视表
Schema::create('jobs_job_types', function (Blueprint $table) {
$table->increments('id');
$table->integer('jobs_id')->unsigned()->nullable();
$table->integer('job_types_id')->unsigned()->nullable();
$table->timestamps();
$table->foreign('jobs_id')->references('id')->on('jobs');
$table->foreign('job_types_id')->references('id')->on('job_types');
});
控制器
$data = \App\JobTypes::paginate($items);
return view('jobs.index', compact('data'))->with(array('showData' => $showData, 'count' => $count))->withItems($items);
看法
@foreach($data as $jobType)
<td>
@foreach($jobType->jobs as $category)
{{ $category->name }}
@endforeach
</td>
@endforeach
我错过了什么吗?