Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - Inserting multiple records when using the hasMany relationship

Still finding my feet with Laravel 4 and I'm a little unsure as to why this isn't working.

In L3 I was able to insert multiple records to a table like so...

$comments = array(
    array('message' => 'A new comment.'),
    array('message' => 'A second comment.'),
);

$post = Post::find(1);

$post->comments()->save($comments);

However when I try to do similar now either the records are inserted without the foreign key, like so...

$comments = array(
    array('message' => 'A new comment.'),
    array('message' => 'A second comment.'),
);

$post = Post::first();

$post->comments()->insert($comments);

Or (and after some Googling) I try the following and get a preg_match() expects parameter 2 to be string, array given

$comments = new Comment(array(
    array('message' => 'A new comment.'),
    array('message' => 'A second comment.'),
));

$post = Post::first();

$post->comments()->save($comments);

As well as ...->save($comments) I've tried ...->saveMany() and ...->associate() but I have the same issue as the last example.

On a side note, I do realise that I've wrapped the multidimensional array in an object but that appears to be the correct way to do this. I have tried not doing but that also fails.

I should probably point out that I'm running a seed command through artisan.

Edit: This is the full preg_match error from the log file

[2013-11-27 16:43:39] log.ERROR: exception 'ErrorException' with message 'preg_match() expects parameter 2 to be string, array given' in /Applications/MAMP/htdocs/project/www/bootstrap/compiled.php:6315

like image 709
LiquidB Avatar asked Nov 27 '13 16:11

LiquidB


People also ask

How do you put data in a relation in laravel?

Code: $user = new User; $inputArry = array('data1' => $request['field1'], 'data2' => $request['field2'], 'data3' => $request['field3'], ); $user->create($inputArry); $user->xyz()->create([ 'user_id' => $user->id, 'name' => $request['name'], 'about' => $request['desc'], 'tag' => $request['tag'], ]);

Has one through relationship Laravel example?

Laravel hasOneThrough Relationship The “has-one-through” relationship links models through a single intermediate relation. For example, if each supplier has one product, and each product is associated with only one order, then the supplier model may access the product's order through the product.


2 Answers

This may not be exactly what you are looking for, since it's not using Eloquent, but it should get your seeds done. You can use DB::insert(), like this:

$postId = 1;

DB::table('comments')->insert(array(
    array(
        'message' => 'A new comment.',
        'post_id' => $postId),
    array(
        'message' => 'A second comment', 
        'post_id' => $postId
    ),
));

As an alternative, you could do this using Eloquent too, but it should be done in the opposite way: setting the related model in the "childs". This is what the official docs say:

Associating Models (Belongs To)

When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model

I think it's done this way because in the database, the "child" model is the one which contains the foreign key to the "parent" (in this case, post_id).

The code should look like this:

$post = Post::find(1);

$comments = array(
    array('message' => 'A new comment.'),
    array('message' => 'A second comment.'),
);

foreach ($comments as $commentAttributes) {
    $comment = new Comment($commentAttributes);
    $comment->post()->associate($post);
    $comment->save();
}
like image 146
Manuel Pedrera Avatar answered Dec 10 '22 16:12

Manuel Pedrera


save() expects a single model, saveMany() expects an array of models, and not assoicative array of the data.

But saveMany() will not insert with a single query, it will actually loop trough the models and insert one by one (note: L3 also did this).

If you need to insert a larger set of records don't use the ORM, use the query builder, how Manuel Pedrera wrote the first example code.

Just for the record here is how you would use saveMany():

$post = Post::find(1);

$comments = array(
    new Comment(array('message' => 'A new comment.')),
    new Comment(array('message' => 'A second comment.')),
);

$post->comments()->saveMany($comments);
like image 25
TLGreg Avatar answered Dec 10 '22 18:12

TLGreg