【发布时间】:2021-07-06 02:58:27
【问题描述】:
当我尝试在 Laravel 中检索多对多关系数据时出现错误。错误信息是
SQLSTATE[23000]:完整性约束违规:1052 where 子句中的列“id”不明确(SQL:select * from
jobswhere(不存在(select * fromjob_typesinner joinjob_types_jobson @987654326 @.id=job_types_jobs.job_types_id其中jobs.id=job_types_jobs.jobs_id和job_types.job_types.deleted_at为空)或存在(从@9876543 中选择* *在job_types.id上加入job_types_jobs=job_types_jobs.job_types_id其中jobs.id=job_types_jobs.jobs_id和job_types_jobs= 3 和job_types_jobsjob_types_jobs= 3 和@98为空)和nameLIKE %%)和jobs.deleted_at为空)
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');
});
【问题讨论】:
-
你的
JobTypes模型真的叫jobTypes或JobTypes吗?在Jobs.php中更改它。另外,为什么parent有belongsToMany的关系——和child一样? -
它是
JobTypes。父母或孩子只是对我的描述。 -
但不应该是
belongsToManyforJob->JobType和hasManyforJobType->Job?这将代表关系的双方。请尝试一下,看看这是否能解决或改变您的问题。 -
``` 未找到列:1054 'where 子句'中的未知列 'jobs.job_types_id'(SQL:select * from
jobswherejobs.job_types_id= 3 和 @987654373 @.job_types_id不为空,jobs.deleted_at为空)``` -
您的迁移情况如何?
标签: laravel laravel-5 relational-database relationship