![](/img/trans.png)
[英]How to insert the auto incremented field id of mysql in php and update the id of one table to another?
[英]How to auto insert parent id into another table?
我有两个表,分别是“ applicants
和“ jobs
。 我正在使用Laravel 5.2 。
工作表:
id | job_tittle | email |...
-----------------------------
1 | Engineer | info@mail.com |...
申请人表:
id | job_id | name |...
-----------------------------
1 | 1 | john |...
现在我想当有人针对某份工作提交申请表时,job_id会自动插入到applicants
表中。
到目前为止,我已经尝试了ApplicantController:
$jobAll = Job::all();
$jobId = Job::find($jobAll->first()->id);
//$jobId = $jobAll->first()->id;
DB::table('applicants')->insert([
'job_id' => $jobId,
]);
但是它不起作用。有人可以告诉我我该怎么做吗? 提前致谢。
我认为您应该尝试这样做:
$jobAll = Job::all();
$jobId = $jobAll->first()->id;
DB::table('applicants')->insert([
'job_id' => $jobId,
]);
更新
//Insert for all data
$apllicantsId = DB::table('applicants')->insertGetId([
'name' => $name,
......
]);
$jobAll = Job::all();
$jobId = $jobAll->first()->id;
//insert job id
DB::table('applicants')
->where('id',$apllicantsId)
->Update([
'job_id' => $jobId,
]);
要么
$jobAll = Job::all();
$jobId = $jobAll->first()->id;
//Insert for all data with job id
$apllicantsId = DB::table('applicants')->insertGetId([
'job_id' => $jobId,
'name' => $name,
......
]);
希望这项工作对您有帮助!
尝试这个 :
$job = Job::find($id);
$jodId = $job->id;
DB::table('applicants')->insert([
'job_id' => $jobId,
]);
这将为您工作:
$job = Job::find($id);
DB::table('applicants')->insert(['job_id' => $job->id]);
使用Eloquent时,可以在Job
模型中定义一个关系 :
public function applicants()
{
return $this->hasMany('App\Applicant');
}
然后在创建申请人时使用它:
$job = Job::find($id);
$job->applicants()->create($applicantData);
更新您已经在注释中显示了store()
方法,因此在这种情况下,不要使用DB::insert()
做到这一点:
$job = Job::find($id);
$applicant['job_id'] = $job->id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.