Adham Zahran
Adham Zahran

Reputation: 2180

belongsTo relationship returns null

I have a table called Locins (locations) which has a foreign key to another table called Rgn (regions).

So in my Locin model:

class Locin extends Model
{
    protected $table = 'Locin';

    protected $primaryKey = 'Locin_id';

    public $timestamps = false;

    public function Rgn()
    {
        return $this->belongsTo('App\Models\Rgn', 'RgnID', 'RgnID');
    }
}

and in my Rgn Model:

class Rgn extends Model
{
    protected $table = 'Rgns';

    protected $primaryKey = 'RgnID';

    public $timestamps = false;

    public function Locin()
    {
        return $this->hasOne('App\Models\Locin', 'RgnID', 'RgnID');
    }

}

When I say: $location = Locin::find($request->Locin); a location is returned successfully. (I var_dumped it).

But then when I say $location->Rgn it returns null.

Tables structure:

Locins Table: [Locin_id (primary key), RgnID (foreign key), other unrelated fields].

Rgns Table: [RgnID (primary key), other unrelated fields]

What am I doing wrong?

edit It turns out that the stupid seed in the DB had a foreign key for an entry that does not exist. I am tired of getting stuck on silly things. Sorry and have a good day.

Upvotes: 2

Views: 794

Answers (3)

Sanjay S
Sanjay S

Reputation: 122

If you are fetching the region by the location model then you should use the eager loading (https://laravel.com/docs/5.2/eloquent-relationships#eager-loading) of the related model by using this

$location = Locin::where('Locin_id', $request->Locin)->with('Rgn')->get();

Hope this helps you to find a very quick solution.

Upvotes: 0

Alfredo EM
Alfredo EM

Reputation: 2069

You can see what the query is running for the region, it is a way of testing processes:

\DB::connection()->enableQueryLog();
$location = Locin::find(1);

$region = $location->Rgn;

$query = \DB::getQueryLog();
$lastQuery = end($query);

dd($lastQuery);

You get something like this

array:3 [
    "query" => "select * from `Rgns` where `Rgns`.`RgnID` = ? limit 1"
    "bindings" => array:1 [▼
        0 => 1
    ]
    "time" => 0.5
]

And replacing the value of bindings in the query you could run the output directly to your database to see if the query is correct

Select * from `Rgns` where `Rgns`.`RgnID` = 1 limit 1

Upvotes: 1

Stephan-v
Stephan-v

Reputation: 20289

You have set both relationship columns to 'RgnID' for each relationship. I'm guessing it should be something else.

Remember it is:

return $this->belongsTo('App\Whatever', 'foreign_key', 'other_key');

Upvotes: 0

Related Questions