【发布时间】:2022-02-03 05:45:36
【问题描述】:
伙计们。我正在尝试从员工表中传递 'officeToSector' id 以使用 id 获取 'sector' 表值。但它不起作用,它告诉我“试图获取非对象的属性‘扇区’”。但是,如果我输入 1 或 2 之类的数字,我可以访问该属性。我检查了返回查询的类型,它是一个对象而不是数组...
请你们帮我找出问题所在。非常感谢。
$employees = $this->employeeRepository->listEmployees();
return Datatables::of($employees)
->addColumn('department', function($employee){
// if I assign 2 to $id, I got the return value,
// but it I use the emp->dept_id, I get the non-object error
$id = (int)$employee->department_id;
$sector = OfficeToSector::find($id);
return $sector->sector->name;
)}
->rawColumns(['department'])
->make(true);
officeToSector 模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
// use Illuminate\Database\Eloquent\Relations\Pivot;
class OfficeToSector extends Model
{
protected $table = 'office_to_sectors';
/**
* @var array
*/
protected $fillable = ['office_id','sector_id'];
public function office()
{
return $this->belongsTo(Office::class, 'office_id', 'id');
}
public function sector()
{
return $this->belongsTo(Sector::class, 'sector_id');
}
public function employee()
{
return $this->hasMany(Employee::class, 'employee_id', 'id');
}
public function registeredDepartment()
{
return $this->hasOne(DepartmentContent::class, 'department_id');
}
}
部门模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Sector extends Model
{
/**
* @var array
*/
protected $fillable = ['name','status'];
/**
* @var array
*/
protected $casts = [
'status' => 'boolean',
];
public function offices()
{
return $this->belongsToMany('App\Models\Office', 'office_to_sectors')->withPivot('sector_id', 'office_id')->withTimestamps();
}
}
【问题讨论】:
标签: laravel eloquent foreign-keys one-to-many