1

I have 3 tables

bank(id, title), 

employee(id, name, bank_id), 

payroll(id, employee_id, salary).

Now I want to retrieve bank title of employee_id in payroll table.

I have set model relationships

class Bank extends Model
{
    public function employees()
    {
       return $this->hasMany('App\Employee');
    }
}


class Employee extends Model
{
    public function bank()
    {
        return $this->belongsTo('App\Bank');
    }

    public function payrolls()
    {
       return $this->hasMany('App\Payroll');
    }
}

class Payroll extends Model
{
    public function employee()
    {
        return $this->belongsTo('App\Employee');
    }
 }

I have tried to retrieve using $payroll->employee->bank->title. But it did not help me

Piazzi
  • 2,490
  • 3
  • 11
  • 25
Raja Durai
  • 65
  • 1
  • 10

2 Answers2

0

Sorry it was my mistake. some employee ids are not referencing bank. That was why I got error. I resolved the issue by using isset method to verify reference value set or not.

Thanks.

Raja Durai
  • 65
  • 1
  • 10
-2

try to change your code a little bit and try again:

 public function bank()
 {
        return $this->hasOne('App\Bank');
  }

Read Laravel Official Documentation /** We can define the inverse of a hasOne relationship using the belongsTo method: **/

Osama Alvi
  • 659
  • 4
  • 14