首页 > 解决方案 > Laravel 5.8 中的多对多关系错误

问题描述

当我尝试在 Laravel 中检索多对多关系数据时出现错误。错误消息是

SQLSTATE [23000]:完整性约束违规:1052 where 子句中的列 'id' 不明确(SQL:select * from jobswhere(不存在(select * from job_typesinner join job_types_jobson job_types. id= job_types_jobs. job_types_idwhere jobs. id= job_types_jobs. jobs_idand job_types. deleted_atis null)或存在(select * from job_typesinner join job_types_jobson job_types. id= job_types_jobs. job_types_idwhere jobs. id= job_types_jobs. jobs_idand id= 3 and job_types. deleted_atis null) and nameLIKE %%) and jobs. deleted_atis null)

桌子 在此处输入图像描述

JobTypes.php

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

乔布斯.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');
    });

标签: laravellaravel-5relational-databaserelationship

解决方案


您正在偏离 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');
});

推荐阅读