Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert record with many belongsTo relations in Laravel Eloquent

I am trying to insert record in Eloquent way.

It is clear in basic cases. For example if I have a Blog with Posts and each post belongs to a User I can do this:

$post = new Post;
$post->content = 'Post content';
$user->posts()->save($post);

But how should I do this if my Post belongs to User, Category and Group at the same time?

My first idea was to do it this way:

$post = new Post;
$post->content = 'Post content';
$user->posts()->save($post);
$group->posts()->associate($post);
$cat->posts()->associate($post);

But it doesn't work, because group id and category id are null when I save it to the DB and it is not allowed.

What I am doing now is:

$post = new Post;
$post->content = 'Post content';
$post->group = $group->id;
$post->category = $cat->id;
$user->posts()->save($post);

But I don't think it is the right way.

Could someone point me in the right direction?

like image 456
TheJohnny Avatar asked Jan 04 '15 12:01

TheJohnny


People also ask

How do you define many relationships in Laravel?

As we have defined the hasMany relationship on Brand model which return the related records of Product model, we can define the inverse relationship on the Product model. Open your app/Product. php model file and add a new method called brand() in it which will return the related brand of a product.

Does Laravel have many through relations?

Eloquent Relationships is one of the most useful and powerful features of the Laravel Framework. It is one of the reasons why I like Laravel most. Mainly it helps us to fetch or insert data in a very easy and efficient way.


1 Answers

You're using associate the wrong way around. You have to call it on the belongsTo relation side not the hasMany.

Try this:

$post = new Post;
$post->content = 'Post content';
$post->category()->associate($cat);
$post->group()->associate($group);
$user->posts()->save($post);
like image 151
lukasgeiter Avatar answered Sep 21 '22 16:09

lukasgeiter