如何自动将父ID插入另一个表?

时间:2017-01-17 04:44:41

标签: php mysql laravel laravel-5.2

我有一个名为applicantsjobs的两个表。我正在使用 Laravel 5.2

职位表:

id | job_tittle | email         |...
-----------------------------  
1  | Engineer   | info@mail.com |...

申请人表:

id | job_id | name |...
-----------------------------  
1  |   1    | john |...

现在我希望当有人针对某个工作提交申请表时,会在applicants表中自动插入job_id。

到目前为止我已尝试过 ApplicantController:

$jobAll = Job::all();
$jobId = Job::find($jobAll->first()->id);
//$jobId = $jobAll->first()->id;

DB::table('applicants')->insert([
'job_id' => $jobId,
]);

但它没有用。有人能告诉我怎么办?提前谢谢。

3 个答案:

答案 0 :(得分:1)

我想你应该试试这个:

$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,
   ......
 ]);

希望这对你有用!

答案 1 :(得分:0)

试试这个:

$job = Job::find($id);
$jodId = $job->id;

DB::table('applicants')->insert([
'job_id' => $jobId,
]);

答案 2 :(得分:0)

这对你有用:

$job = Job::find($id);
DB::table('applicants')->insert(['job_id' => $job->id]);

当您使用Eloquent时,您可以在Job模型中define a relationship

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;