okconfused
okconfused

Reputation: 3637

associate function is not working in hasMany relation Laravel

I am using Laravel 5.3 ad having issues on saving through the hasMany relationship.

I have tables job and jobsite which has One-to-Many Relation i.e Each jobsite has one or many jobs

but when I am trying to add job_job_site_id in the job table using associate() it send me an error:

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 ...
^

Database structure:

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

Model Class Job:

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

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_job_site_id', 'job_id');
    }
}

Controller:

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

Do I have my relationship defined incorrectly here?

Upvotes: 1

Views: 1120

Answers (1)

Amit Gupta
Amit Gupta

Reputation: 17658

Yes, your have defined relationships incorrectly. The correct version is following:

Model Class Job:

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

Upvotes: 1

Related Questions