Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel How to update one to one relationships?

Terms table:

  • term_id
  • name
  • slug

Term_taxonomy table:

  • term_taxonomy_id
  • term_id
  • description

My Term model:

public function TermTaxonomy(){
    return $this->hasOne('TermTaxonomy');
}

My TermTaxonomy model:

public function Term(){
    return $this->belongsTo('Term');
}

My Categories controller:

public function update($id){
    echo "$id"; // echo success
    echo $data['name']; // it should update name field in term table
    echo $data['slug']; // it should update slug field in term table
    echo $data['TermTaxonomy']['description']; // it should update description field in termtaxonomy table
}

how i can update one to one relationships ? maybe with push()

Thanks, sorry i am new in laravel.

like image 959
Dark Cyber Avatar asked Jan 26 '15 03:01

Dark Cyber


2 Answers

You can use Eloquent's update() method: https://laravel.com/docs/5.4/eloquent#updates

$Term = Term::with('TermTaxonomy')->find($id);
$Term->name = $data['name'];
$Term->slug = $data['slug'];

// Save The Term first
$Term->save();

// Now update the relation
$Term->TermTaxonomy->update([
    'taxonomy' => 'category',
    'description' => $data['TermTaxonomy']['description']
]);
like image 160
crabbly Avatar answered Oct 19 '22 13:10

crabbly


as Jarek Tkaczyk comment in this question Laravel eloquent: Update A Model And its Relationships

There is no other way, as Eloquent currently doesn't know what relations are on the model until you call them as dynamic property, load with load method, eager load etc. (push works only with loaded relations that are present in model's relations array)

so i use this code.

$Term = Term::with('TermTaxonomy')->find($id);
$Term->name = $data['name'];
$Term->slug = $data['slug'];
$Term->TermTaxonomy->taxonomy = 'category';
$Term->TermTaxonomy->description = $data['TermTaxonomy']['description'];
$Term->push();

and it works. Term and TermTaxonomy table is updated, but if change push() to save() it only update Term table even TermTaxonomy relationships already loaded with Eager load Term::with('TermTaxonomy')

Thanks for all :D

like image 30
Dark Cyber Avatar answered Oct 19 '22 12:10

Dark Cyber