2

我有 2 张桌子employeesemployee_locations. 一名员工有许多地点。我需要找出一条员工记录以及相关的最新employee_locations记录。我写了下面的查询。

$employees = Employee::find([1])->with('employees.employee_locations')->latest()->first();

我得到以下错误

BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::with does not exist.
4

3 回答 3

2

您的问题是 find 方法检索 Eloquent 对象的集合,在该集合上不能使用 with 方法。您必须首先指定Employee对象的关系,然后使用 find。

下面的代码将检索find每个员工的方法和位置中指定的 id 的员工:

$employees = Employee::with('employees.employee_locations')->find([1])
于 2019-12-04T10:45:06.257 回答
1

在模型中创建关系。像这样的东西:

class Employee extends Model
{

    protected $table = 'employees';

    public function location()
    {
        return $this->hasMany(EmployeeLocation::class, 'employeed_id');
    }
}

class EmployeeLocation extends Model
{
    protected $table = 'employee_locations';
}

$employees = Employee::with('location')->first();
or you do
$employees = Employee::with('location')->find(<employeed_id>);
于 2019-12-04T10:52:45.743 回答
0

试试这个方法

$employees = Employee::with('employees')->where('employeesid',$employeesid)- 
>get()->find($employeesid);
于 2019-12-04T10:58:51.480 回答