mercredi 6 avril 2016

Laravel: Updating hasMany/BelongTo relation

I have a master table jobs with multiple location in separate table job_location. Now I am not able to update/delete, if extra rows found from job_location. Now why I am saying DELETE is because sync() did this, but it's related to many-to-many relation. I am new to laravel, just trying to get eloquent approach to achieve this, otherwise deleting all rows and inserting can be done easily OR updating each and delete remaining is also an option but I wonder Laravel has something for this.

In every request I get multiple job locations(with unchanged/changed city,phone_number,address) which is creating trouble.

Some codeshots:

Model: [Job]

class Jobs extends Model
{
    protected $fillable = [
        'job_id_pk', 'job_name','salary'
    ];


    public function joblocation() {
        return $this->hasMany('\App\JobLocation', 'job_id_fk', 'job_id_pk');
    }

}


Model:[JobLocation]

class JobLocation extends Model
{
    protected $fillable = [
        'jobl_id_pk', 'job_id_fk','city', 'address', 'phone_number'
    ];


    public function job() {
        return $this->belongsTo('\App\Jobs', 'job_id_fk', 'job_id_pk');
    }

}

Controller:[JobController]

function jobDetail() {

    if($params['jid']) {    
        // update
        $obj = \App\Jobs::find($params['jid']);
        $obj->job_name = $params['name'];
        $obj->salary = $params['salary'];
        $obj->save();
    } else {        
        // create new
        $data = array(
            'job_name' => $params['name'],
            'salary' => $params['salary'],
        );
        $obj = \App\Jobs::create($data);
    }

    // don't bother how this $objDetail has associative array data, it is processed so
    foreach ($params['jobLocations'] AS $key => $objDetail) {
        $jobLoc = new \App\JobLocation;
        $jobLoc->city = $objDetail['city'];
        $jobLoc->phone_number = $objDetail['phone_number'];
        $jobLoc->address = $objDetail['address'];

        $jobLoc->job()->associate($obj);
        $obj->jobLoc()->save($jobLoc);
    }

}

In this approach I am able to save all job locations, but I am using same function to update also. Please tell how I can update jobLocations if present. I am ok to loose previous entries, but it would be good if previous gets updated and new get entered OR if we have extra entries they get deleted. I know sounds weird but still guide me a way.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire