关联函数在hasMany关系Laravel中不起作用

时间:2016-11-13 15:43:00

标签: php laravel eloquent one-to-many laravel-5.3

我使用的Laravel 5.3广告在通过hasMany关系进行保存方面存在问题。

我有桌面工作和工地,有一对多关系,即每个工地有一个或多个工作

但是当我尝试使用job_job_site_id在作业表中添加associate()时,它会向我发送错误消息:

SQLSTATE[42703]: Undefined column: 7 ERROR: column "job_site" of relation "job" does not exist
LINE 1: update "job" set "updated_at" = $1, "job_site" = $2 ...
^ (SQL: update "job" set "updated_at" = 2016-11-13 15:29:37, "job_site" = where "job_id" = 3)

SQLSTATE[42703]: Undefined column: 7 ERROR: column "job_site" of relation "job" does not exist
LINE 1: update "job" set "updated_at" = $1, "job_site" = $2 ...
^

数据库结构:

job (1st table)
– job_id
– job_name
– job_job_site_id
- created_at
- updated_at

job_site (2nd table)
– job_site_id
– job_site_name
- created_at
- updated_at

模特职业:

class Job extends Model
{
    protected $table = 'job';
    protected $primaryKey = 'job_id';

    public function jobsite() {
        return $this->belongsTo('App\Models\JobSite', 'job_site', 'job_job_site_id', 'job_site_id');
    }
}   

模型类JobSite:

class JobSite extends Model
{
    protected $table = 'job_site';
    protected $primaryKey = 'job_site_id';

    public function jobs() {
        return $this->hasMany('App\Models\Job', 'job', 'job_job_site_id', 'job_id');
    }
}

控制器:

public function jobsiteJobs($data)
{
    $jobsite = JobSite::find(3);
    $job_id = array(1,2,3);
    if (!empty($jobsite)) {
        foreach ($job_id as $id) {
            $job = Job::find($id);
            $job->jobsite()->associate($jobsite);
            $job->save();
        }
        return 'Added';
    }   
    else {
        return 'Not found';
    }
}

我的关系定义不正确吗?

1 个答案:

答案 0 :(得分:1)

是的,您已经错误地定义了关系。正确的版本如下:

模特职业:

class Job extends Model
{
    protected $table = 'job';
    protected $primaryKey = 'job_id';

    public function jobsite() {
        return $this->belongsTo('App\Models\JobSite', 'job_job_site_id', 'job_site_id');
    }
}   

Model Class JobSite:

class JobSite extends Model
{
    protected $table = 'job_site';
    protected $primaryKey = 'job_site_id';

    public function jobs() {
        return $this->hasMany('App\Models\Job', 'job_job_site_id', 'job_site_id');
    }
}