无法检索 Laravel 中的一对多关系数据

Can't Retrieve One to Many Relationship Data In Laravel

关于在 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');
}

旋转 table

 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 

我是不是漏掉了什么?

这样试试:

// JobTypes model
public function jobs()
{
    // one type of job has many jobs
    return $this->hasMany(\App\Job_Type::class, 'job_id');
}

// Jobs model
public function job_types()
{
    // one job only belongs to one type of job
    return $this->belongsTo('App\jobTypes','job_type_id','id');
}

Laravel 中的 one-to-many relationship 不需要枢轴 table。子关系(“多”方)可以简单地存储它所属的父模型的 id。

(另请参阅我上面关于遵循一般 Laravel naming conventions 的评论。)

型号:

// JobType.php
class JobType extends Model
{
    public function jobs()
    {
        return $this->hasMany('App\Job');
    }
}

// Job.php
class Job extends Model
{
    public function job_type()
    {
        return $this->belongsTo('App\JobType');
    }
}

迁移:

// create_job_types_table.php
    Schema::create('job_types', function (Blueprint $table) {
        $table->increments('id');
        ...
    });

// create_jobs_table.php
    Schema::create('jobs', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('job_type_id')->unsigned()->index();
        ...

        $table->foreign('job_type_id')->references('id')->on('job_types');
    });