Laravel Records关系问题

时间:2017-06-08 07:36:28

标签: php database laravel laravel-5 eloquent

我在ApplicantpendingJob之间有一对多的关系,我的申请人模型有cnic 主键,其中pendingJob有{ {1}}并将其指向applicant_id model cnic列作为外键。

申请人型号:

Applicant

PendingJob模型:

protected $primaryKey = 'cnic';

public function pending_jobs() {
    return $this->hasMany('App\PendingJobs', 'applicant_id');
}

我在申请人中插入记录,如:

public function applicant() {
    return $this->belongsTo('App\Applicant', 'applicant_id');
}

然后记录在$req = new \App\Applicant; $req->full_name = $request->get('full_name'); $req->cnic = $request->get('cnic'); $req->mobile_number = $request->get('mobile_number'); $req->save();

PendingJob

记录保存并$reqr = new \App\PendingJob; $reqr->applicant_id = $request->get('cnic'); $reqr->job_type = 'residence'; $reqr->status = 'pending'; $reqr->save(); cnic primary key Applicant Pendingjob applicant_id指向Applicant } cnic来了。

但是

关系不加载,phpmydamin手动记录插入工作正常。

1 个答案:

答案 0 :(得分:1)

工作流程应为:

$reqr = new \App\PendingJob;
$reqr->job_type = 'residence';
$reqr->status = 'pending';

$req = new \App\Applicant;
$req->full_name = $request->get('full_name');
$req->cnic = $request->get('cnic');
$req->mobile_number = $request->get('mobile_number');

$reqr->applicant()->associate($req);

$reqr->save();

来源:https://laravel.com/docs/5.4/eloquent-relationships#the-save-method

此外,我注意到申请人的主要密钥是cnic,因此您的关系应根据Laravel文档指定local_key

App\Application

public function pending_jobs() {
    return $this->hasMany('App\PendingJobs', 'applicant_id', 'cnic');
}

App\PendingJob

public function applicant() {
    return $this->belongsTo('App\Applicant', 'applicant_id', 'id');
}