laravel - Laravel 5.8 中的多对多关系错误
问题描述
当我尝试在 Laravel 中检索多对多关系数据时出现错误。错误消息是
SQLSTATE [23000]:完整性约束违规:1052 where 子句中的列 'id' 不明确(SQL:select * from
jobs
where(不存在(select * fromjob_types
inner joinjob_types_jobs
onjob_types
.id
=job_types_jobs
.job_types_id
wherejobs
.id
=job_types_jobs
.jobs_id
andjob_types
.deleted_at
is null)或存在(select * fromjob_types
inner joinjob_types_jobs
onjob_types
.id
=job_types_jobs
.job_types_id
wherejobs
.id
=job_types_jobs
.jobs_id
andid
= 3 andjob_types
.deleted_at
is null) andname
LIKE %%) andjobs
.deleted_at
is 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');
});
解决方案
您正在偏离 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');
});
推荐阅读
- android - BraintreeBrowserSwitchActivity 丢失错误
- javascript - Rollup + HoCs treeshaking
- julia - 如何让 Julia 在我的项目目录中创建 ./test/runtests.jl
- phpmyadmin - 当我收到已损坏的错误消息时,如何在 phpmyadmin 中修复我的用户数据库表?
- swift - 在 Swift 中使用 patternImage 不居中的图像
- angular - TypeError:无法读取未定义的属性“长度”(Angular 8)(标题)
- ruby-on-rails - 如何使用 Mail gem 在转发中查找原始电子邮件
- bitbucket - 如何在 Bitbucket Pipelines 中触发 webhook
- c# - 自定义 nopCommerce 插件在本地构建后安装良好,但通过界面上传后不会从 .zip 中提取
- python - 将一个字典解压到单独的字典中