Laravel 5.8 中的多对多关系错误

Error Many to Many Relationship in Laravel 5.8

我在 Laravel 中尝试检索多对多关系数据时遇到错误。错误信息是

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from jobs where (not exists (select * from job_types inner join job_types_jobs on job_types.id = job_types_jobs.job_types_id where jobs.id = job_types_jobs.jobs_id and job_types.deleted_at is null) or exists (select * from job_types inner join job_types_jobs on job_types.id = job_types_jobs.job_types_id where jobs.id = job_types_jobs.jobs_id and id = 3 and job_types.deleted_at is null) and name LIKE %%) and jobs.deleted_at is null)

Table

JobTypes.php

public function jobs() // children  
{
    // one type of job has many jobs
    return $this->belongsToMany('App\Jobs'); // id refer to jobs.id
}

Jobs.php

public function job_types() // parent 
{
    // one job only belongs to one type of job
    return $this->belongsToMany('App\jobTypes');
}

JobTypeController.php

public function assignJob($id)
{
    $jobType = \App\JobTypes::withTrashed()->find($id);
    $jobs = $jobType->jobs;

    return view('job-types.assign-job', compact(['jobType', 'jobs']));
}

查看

<label for="name">Job</label>
                <select selected="selected" multiple class="form-control {{ $errors->first('jobs') ? "is-invalid" : "" }}" name="jobs[]" id="jobs" class="jobs"></select>
                <div class="invalid-feedback">
                    {{ $errors->first('jobs') }}
                </div>

迁移

Schema::create('job_types', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });

    Schema::create('jobs', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });

    Schema::create('jobs_job_types', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('jobs_id')->unsigned()->index();
        $table->integer('job_types_id')->unsigned()->index();

        $table->foreign('jobs_id')->references('id')->on('jobs')->onDelete('cascade');
        $table->foreign('job_types_id')->references('id')->on('job_types')->onDelete('cascade');
    });

您偏离了 Eloquent 用于标识不同表中字段的默认命名方案。目前,您在列中使用复数形式(例如 jobs_id),但 Eloquent 假定为单数形式 (´job_id`).

job_job_type 迁移文件中,将所有列名称和模式名称更改为 单数 名称。在 运行 migrate:refresh(即更新数据库模式)之后,Eloquent 将能够自动将关系映射到数据库中的模式。

Schema::create('job_job_type', function (Blueprint $table) {
  $table->increments('id');
  $table->integer('job_id')->unsigned()->index();
  $table->integer('job_type_id')->unsigned()->index();
    
  $table->foreign('job_id')->references('id')->on('jobs')->onDelete('cascade');
  $table->foreign('job_type_id')->references('id')->on('job_types')->onDelete('cascade');
});