Adam Zahran Adam Zahran - 1 year ago 77
PHP Question

belongsTo relationship returns null

I have a table called

(locations) which has a foreign key to another table called

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
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?

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.

Answer Source

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

$location = Locin::find(1);

$region = $location->Rgn;

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


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download