Skip to content
Advertisement

Laravel: belongsTo() relation assume one-to-many relationship instead of one-to-one

I’m having a tedious problem with Laravel’s ORM.

I have a model with multiple relationships, like this:

JavaScript

Now I can access the template related item in a simple way, like this:

JavaScript

And it works out of the bat, because Laravel’s ORM assumes it is a one-to-one relationship and internally calls the first() method.

But when I try the same with updateUser it fails, returning an error, saying that it can’t call name on a non-object.

But if I try this:

JavaScript

it works, but it doesn’t feel right to me.

So my question is, how Laravel’s ORM decide if a relationship defined with belongsTo() is one-to-one or one-to-many? Is there a way to force a needed behaviour?

Thanks

Advertisement

Answer

You need to define the relationship. You can define ‘different’ relationships on the perspective.

The ->belongsTo() function is an inverse function – but you havent defined anything on the users table – so it is wrongly assuming the inverse is one-to-many.

Just add this to your users class:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement