【问题标题】:Retrieve related model querying with a pivot table column value使用数据透视表列值检索相关模型查询
【发布时间】:2022-02-03 10:01:35
【问题描述】:

我有一个 Employee 模型,它有一个通过 belongsToMany 关系 agents() 访问的数据透视表 customer_employee(employee_id、customer_id、token) :

class Employee extends Model {
    ...
    public function agents(): BelongsToMany
    {
        return $this->belongsToMany(Employee::class)->withPivot('token');
    }

我想查询(在 Eloquent 中)de 数据库以获取其代理令牌 == 'abc' 的 Employee 模型。

谁能帮帮我?谢谢和问候。

(1) token(employee_id, customer_id) 是唯一的

(2) 在原始 sql 中是

$sql = 'select employee.*
        from employee inner join customer_employee
        on employee.id = customer_employee.employee_id
        where customer_employee.token = "abc"';

【问题讨论】:

标签: laravel eloquent relationship


【解决方案1】:

我认为 Laravel 在 whereHas 上加入了数据透视表,所以你可以尝试这样的事情:

        Employee::whereHas('agents', function ($query) {
            $query
                ->where('customer_employee.token', 'the_token');
        })->first();

您也可以使用 [wherePivot][1] 尝试自定义关系

public function agents($token): BelongsToMany
            {
                return $this->belongsToMany(Employee::class)->withPivot('token')->wherePivot('token', $token);
            }

另外你的模型是Employee,你的代理关系也是Employee。模型应该是客户吗? [1]:https://laravel.com/docs/8.x/eloquent-relationships#filtering-queries-via-intermediate-table-columns

【讨论】:

  • 非常感谢您的回答Mtxz。我首先尝试您的第二个选项,但我不知道如何调用它。如果我执行$result = Employee::agents('the_token'),则会收到错误:不能静态调用非静态方法 App\Models\Employee::agents()。如果我创建一个辅助变量$aux = new Employee; 然后$result = $aux->agents(''the_token''); 返回一个空值。
  • 我想我犯了一个错误:我的第二个示例将只查询 1 个具有隶属于员工的代理的令牌。并非所有员工都符合您的令牌规则。所以你应该使用第一个解决方案,无论如何这是最好的。
  • 第一个解决方案效果很好。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多