0
votes

as offical documentation says :

Sometimes you may wish to save not only a model, but also all of its relationships. To do so, you may use the push method: Saving A Model And Relationships $user->push();

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 CategoriesController

public  function store(){
    $data = Input::all();
    $category = new Term;
    $category->name = $data['name'];
    $category->slug = $data['slug'];
    $category->TermTaxonomy()->taxonomy = 'category';
    $category->TermTaxonomy()->description  = $data['TermTaxonomy']['description'];
    $category->push();  
}

with my code above, I can save name and slug, but taxonomy and description not inserted. how i can do it with push() instead of save() ? is it possible ?

Thanks, i am new in Laravel.

1

1 Answers

0
votes

As I understand it, the purpose of push() is to update related models not insert them. Because the method just cycles over all loaded related models and saves them:

public function push()
{
    if ( ! $this->save()) return false;

    foreach ($this->relations as $models)
    {
        foreach (Collection::make($models) as $model)
        {
            if ( ! $model->push()) return false;
        }
    }

    return true;
}

So a use case would be this:

$category = Term::find(1);
$category->name = 'foo';
$category->TermTaxonomy->description = 'bar';
$category->push(); // save would only update the name but not the description

I suggest you use the methods Laravel has for inserting related models:

$category = new Term;
$category->name = $data['name'];
$category->slug = $data['slug'];
$taxonomy = new TermTaxonomy();
$taxonomy->taxonomy = 'category';
$taxonomy->description  = $data['TermTaxonomy']['description'];
$category->TermTaxonomy()->save($taxonomy);
$category->save();

Alternatively, if your TermTaxonomy model is configured for mass assignment you can use create()

$category = new Term;
$category->name = $data['name'];
$category->slug = $data['slug'];
$category->TermTaxonomy()->create([
    'taxonomy' => 'category',
    'description' => $data['TermTaxonomy']['description']
]);
$category->save();

If you really wanted to use push(). This would work as well:

$category = new Term;
$category->name = $data['name'];
$category->slug = $data['slug'];
$taxonomy = new TermTaxonomy();
$taxonomy->taxonomy = 'category';
$taxonomy->description  = $data['TermTaxonomy']['description'];
$category->setRelation('TermTaxonomy', $taxonomy);
$category->push();