vanamp
vanamp

Reputation: 53

Laravel 5.3 Eloquent Model Relationship not working, Returns NULL

I am new to Laravel and am struggling with this:

Database - MSSQL existing DB schema cannot be modified as other software depends on it. (not sure if this is a problem or not)

Model/Table setup: INFO_ALL Table - ID is primary key PERSON Table - ID is foriegn key

ID's are hex values and I notice eloquent removes the 0x from the start of the value and am not sure if this is causing the relationship to fail or not. example: in the DB I see 0x123456789 in my returned eloquent data I see 123456789

Person Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Person extends Model
{
protected $table = 'PERSON';
protected $primaryKey = 'ID';
public $incrementing = false;
public $timestamps = false;

    public function info_all(){

        return $this->belongsTo(Info_All::class, 'ID', 'ID');
        }
}

Info Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Info_All extends Model
{
protected $table = 'INFO_ALL';
protected $primaryKey = 'ID';
public $incrementing = false;
public $timestamps = false;

    public function person(){

       return $this->hasOne(Person::class, 'ID', 'ID');

    }
}

How I am testing the relationship:

php artisan tinker
$person = App\Person::first();
$person->info;
NULL

php artisan tinker
$info= App\Info::first();
$info->person;
NULL

I know this relationship exists in the DB and I can manuualy get them together with a query but the relationship feature of this framework would really be nice to get figured out.

Beign new to Laravel there are a few things I am unsure about, like if the third argument in the realationship is neccesary since I am declaring the $primaryKey. I declared the $primarykey in the first model because I assummed it is case sensative and my table has ID not id. That being said, I have been stuck on this for a couple days and feel like I have tested everything in every different combination.

Any help is appreciated.

Upvotes: 0

Views: 667

Answers (1)

Amit Gupta
Amit Gupta

Reputation: 17708

Your relation is defined incorrectly. Try by adding following relation:

Person Model

public function info()
{
   return $this->hasOne(Info_All::class, 'ID', 'ID');
}

Info_All model

public function person()
{
    return $this->belongsTo(Person::class, 'ID', 'ID');
}

Then try it out in tinker:

$person = App\Person::first();
$person->info;

I am not sure but if eloquent removes the 0x from the start of the value then it can also cause the problem.

Try by removing 0x from your tables.

Upvotes: 0

Related Questions