簡體   English   中英

如何自動將父ID插入另一個表?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM