Kasra GH
Kasra GH

Reputation: 157

laravel eloquent relationship getting property on non-object

This is the way I created my database (each employee can have multiple title) :

CREATE TABLE employees (
    emp_no      INT             NOT NULL,
    birth_date  DATE            NOT NULL,
    first_name  VARCHAR(14)     NOT NULL,
    last_name   VARCHAR(16)     NOT NULL,
    gender      ENUM ('M','F')  NOT NULL,    
    hire_date   DATE            NOT NULL,
    PRIMARY KEY (emp_no)
);

CREATE TABLE titles (
    emp_no      INT             NOT NULL,
    title       VARCHAR(50)     NOT NULL,
    from_date   DATE            NOT NULL,
    to_date     DATE,
    FOREIGN KEY (emp_no) REFERENCES employees (emp_no) ON DELETE CASCADE,
    PRIMARY KEY (emp_no,title, from_date)
); 

These are the corresponding models:

class employee extends Model
{
    protected $primaryKey = 'emp_no'; 
    public $incrementing = false; 
    protected $connection = 'testMYSQL';

    public function title()
    {
        return $this->hasMany('App\title', 'emp_no');
    }
}

class title extends Model
{
    protected $primaryKey = ['emp_no', 'title', 'from_date'];
    public $incrementing = false;
    protected $connection = 'testMYSQL';
    public $timestamps = false;

    public function employee()
    {
        return $this->belongsTo('App\employee', 'emp_no');
    }
}

In my controller, I used the models I'd created like this :

return $employee = employee::find(1)->title;

But I get this error for the line above:

"Trying to get property 'title' of non-object"

Update: These work fine though:

return $employee = employee::first()->title;
return $employee = title::first()->employee;

I think the relationships are correct and the problem is that Laravel still hasn't noticed that the primary key is emp_no and not id. I changed $primaryKey type from protected to public but still I get the same error.

Upvotes: 0

Views: 630

Answers (1)

Keval Mangukiya
Keval Mangukiya

Reputation: 2493

Yes, I think error of the find method because untill I know find() method only work on Id(primary key)

And your table has emp_no so,

employee::find(1)->title;

This method is not work and occurred the following errors

"Trying to get property 'title' of non-object"

Upvotes: 0

Related Questions