Relationships Laravel OneToOne? [duplicate]

1

I am doing some exercises, but there is one where I can not understand why it is not working when I make another name in the method. I have a method in Model Location , where it does 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);
}

OneToOne Controller

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

This way returns dd() as null Now if I put it this way

Model Location

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

OneToOne Controller

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

In this last way it returns to me the data, because, with the name in the method countryInverso does not work and only with the name country it works?

    
asked by anonymous 16.08.2017 / 21:29

1 answer

1

Let's look at what Laravel 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, Eloquent will try to match user_id of model Phone with id of model User . But how does he do it ???

Eloquent assumes the name of the default foreign key by examining the relationship method name and only adds the% with%. This means that the foreign key for the Elloquent contained in the _id table in the database will be Phone .

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

How to resolve this issue?

However, if the model null foreign key is not user_id, you can pass a custom key name as the second argument to the Phone method:

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

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

public function countryInverso()
{
    return $this->belongsTo(Country::class, 'country_id');
}
    
17.08.2017 / 13:45