1

When I am creating a snippet model I want to directly add a relational record to the intermediate table but I get this error:

Unhandled Exception

Message: Method [save] is not defined on the Query class.

When I execute this code:

$new_snippet = new Snippet(array('snippet' => Input::get('snippet'), 
                                   'title' => Input::get('title')) );

foreach (Input::get('categorie_ids') as $categorie_id) 
{
    $categorie = Categorie::find($categorie_id)->snippet()->save($new_snippet);
}

I'm relatively new to working with relational models in Laravel so all suggestions on how to do this are welcome.

Community
  • 1
  • 1
Sjaak Rusma
  • 1,424
  • 3
  • 23
  • 36
  • How did you define the relation ship in `Category` with `Snippet`, can you post it? – Rubens Mariuzzo Aug 15 '13 at 15:02
  • Thank you for the reply. I defined as public function snippet() { return $this->has_many_and_belongs_to('Snippet'); } and vice versa. But I solved the problem using attach – Sjaak Rusma Aug 15 '13 at 17:08

1 Answers1

0

After checking the documentation again and trying out some stuff I came up with this solution:

$new_snippet = Snippet::create(array('snippet' => Input::get('snippet'), 'title' => Input::get('title')) );
            foreach (Input::get('categorie_ids') as $categorie_id) {
                $categorie = Categorie::find($categorie_id)->snippet()->attach($categorie_id, array('snippet_id' => $new_snippet->id));
            }

Basically I just used attach instead of save.

Sjaak Rusma
  • 1,424
  • 3
  • 23
  • 36