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:

class Pages extends Eloquent {

    protected $guarded = array('id','config_id');

    public function template()
    {
        return $this->belongsTo('Templates', 'templates_id');
    }

    public function updateUser()
    {
        return $this->belongsTo('Users', 'updated_by');
    }

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

$this->template->name;

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:

$this->updateUser()->first()->name;

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:

class Users extends Eloquent {

    public function pages()
    {
        return $this->hasMany('Pages');
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement