试图获得非对象laravel 5的属性 - 我的错误是什么?

时间:2016-01-20 11:40:23

标签: php laravel laravel-5

我的错误是什么?

Employeecontroller:

public function index()
{
  $employees = Employee::all();
  return view('employee.view_all_employee_details', compact('employees'));
}

员工模型功能:

protected $primaryKey = "emp_id";
protected $with = 'additionaldetails';
public function additionaldetails()
{
 return $this->hasOne('App/EmployeeAdditionalDetail' , 'emp_id' , 'emp_id');
}

EmployeeAdditionalDetail模型:

public function employeeDetails()
{
 return $this->belongsTo('App\Employee' , 'emp_id' , 'emp_id');
}

view_all_employee_details查看

@if(count($employees) > 0)

@foreach($employees as $employee)
    <tr>
        <td> {{ $employee->first_name }} </td>
        <td> {{ $employee->manager_id }} </td>
        <td>

          {{ $employee->additionaldetails->emp_id }}  **Error showing here**
        </td>
    </tr>
@endforeach

@else
   {!! "<tr><td>No Recod Found</td></tr>" !!}

@endif

MyError:

  

尝试获取非对象的属性

1 个答案:

答案 0 :(得分:2)

试试这个

{{ $employee->additionaldetails->emp_id }}

员工模型可以访问basicdetails()函数。您正在尝试使用additionaldetails()获取数据。

也改变了这一行

return $this->hasOne('App/EmployeeAdditionalDetail' , 'emp_id' , 'emp_id');

return $this->hasOne('App\EmployeeAdditionalDetail' , 'emp_id' , 'emp_id');