【发布时间】:2021-04-06 22:43:47
【问题描述】:
我对在 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
我错过了什么吗?
【问题讨论】:
-
建议尽可能遵循通用的 Laravel 命名约定,尤其是在你的模型中,因为这会为你以后省去很多麻烦,并使你的代码更容易被其他 Laravel 开发人员阅读。即
App\jobTypes应为单数大写App\JobType,其对应的数据库表为snake_case和小写job_types。
标签: laravel laravel-5 relationship