【问题标题】:Use find() and with() together in Laravel query在 Laravel 查询中一起使用 find() 和 with()
【发布时间】:2019-12-04 10:22:12
【问题描述】:

我有 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.

【问题讨论】:

    标签: sql eloquent laravel-6.2


    【解决方案1】:

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

    以下代码将检索具有find 方法中指定的 id 的员工以及每个员工的位置:

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

    【讨论】:

    • 我收到Call to undefined relationship [employees] on model [App\Employee]. 错误。
    • 这意味着您的关系在 Employee 模型中没有正确定义。你能向我们展示你的员工模型吗?
    • 谢谢@arm。这是员工模型<?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Employee_location; class Employee extends Model { protected $fillable = ['name', 'emi_number', 'account_id']; public function employee_locations() { return $this->hasMany(Employee_location::class); } }
    • 因为您的关系方法称为employee_locations,您应该在with 函数中使用它,如下所示:with('employee_locations')
    【解决方案2】:

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

    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>);
    

    【讨论】:

    • 我收到Call to undefined relationship [employees] on model [App\Employee]. 错误。
    • 两件事:你定义了employees 关系吗?能分享一下里面的内容吗?
    【解决方案3】:

    试试这个方法

    $employees = Employee::with('employees')->where('employeesid',$employeesid)- 
    >get()->find($employeesid);
    

    【讨论】:

    • 谢谢@Bloody。我收到Call to undefined relationship [employees] on model [App\Employee]. 错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    相关资源
    最近更新 更多