Relationships Laravel Onetoone?

Asked

Viewed 162 times

1

I’m doing some exercises, but there is one but I can’t understand why it’s not working when I do it with another name in the method. I have a method in the Model Location, where he does the relationships of OneToOne.

When I call the method with the simple name it works, more when I call the method with the compound name it from null.

Model Location

public function countryInverso()
{
    return $this->belongsTo(Country::class);
}

Controller Onetoone

public function umPraUmReverso()
{
    $location = Location::where('latitude', 54)->get()->first();
    $country = $location->countryInverso;
    dd($country);
}

Thus returns from dd() null Now if I put it that way

Model Location

public function country()
{
    return $this->belongsTo(Country::class);
}

Controller Onetoone

public function umPraUmReverso()
{
    $location = Location::where('latitude', 54)->get()->first();
    $country = $location->country;
    dd($country);
}

This last way it comes back to me the data, because, with the name in the method countryInverso does not work and only with the name country works?

  • as is the name of the foreign key ?

  • country_id and my foreign key name

1 answer

1


Let’s look at what the Laravel’s documentation on relationships can tell us to solve your problem.

In a relationship One-to-One there is the following example:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

In the example above, the Eloquent will try to combine user_id of model Phone with id of model User. But how does he do it???

The Eloquent presuppose the name of the standard foreign key, examining the name of relationship method and only adds to the method name the _id. That means the foreign key to the Elloquent, contained in the table Phone in the database will be user_id.

This is the reason for your problem. Your foreign key is country_id and only works if the relation method is called country. Any other name will not work. At the time you changed the method name to countryInverso the Elloquent determined that the key name would be countryinverso_id and when searching for such parameter in the database the answer was null.

How to solve this problem?

However, if the foreign key of the model Phone for not user_id, you can pass a custom key name as the second argument for the method belongsTo:

public function user()
{
    return $this->belongsTo('App\User', 'foreign_key');
}

This way you can work with the method name as you like and keep the foreign key name as is. Your case would look like this:

public function countryInverso()
{
    return $this->belongsTo(Country::class, 'country_id');
}
  • 1

    Perfect explanation. Super grateful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.