gpt4 book ai didi

php - Laravel 记录关系问题

转载 作者:搜寻专家 更新时间:2023-10-30 23:34:51 24 4
gpt4 key购买 nike

我在 Applicant 之间有一对多关系和 pendingJob ,我的申请人模型有cnic 主键,其中 pendingJobapplicant_id并将其指向 Applicant将 cnic 列建模为外键。

申请人模型:

protected $primaryKey = 'cnic';

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

PendingJob 模型:

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 keyApplicantPendingjobapplicant_id这是指向 Applicantcnic一样的。

但是

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

最佳答案

工作流程应该是这样的:

$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');
}

关于php - Laravel 记录关系问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com