使用 pivot table 列值检索相关模型查询
Retrieve related model querying with a pivot table column value
我有一个 Employee 模型,它有一个支点 table customer_employee (employee_id , customer_id, token) 通过 belongsToMany 关系访问 agents():
class Employee extends Model {
...
public function agents(): BelongsToMany
{
return $this->belongsToMany(Employee::class)->withPivot('token');
}
并且我想查询(在 Eloquent 中)de 数据库以获取 Employee 模型,其代理的令牌 == 'abc'。
谁能帮帮我?谢谢和问候。
(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 在 whereHas 上加入枢轴 table 所以你可以尝试这样的事情:
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
我有一个 Employee 模型,它有一个支点 table customer_employee (employee_id , customer_id, token) 通过 belongsToMany 关系访问 agents():
class Employee extends Model {
...
public function agents(): BelongsToMany
{
return $this->belongsToMany(Employee::class)->withPivot('token');
}
并且我想查询(在 Eloquent 中)de 数据库以获取 Employee 模型,其代理的令牌 == 'abc'。
谁能帮帮我?谢谢和问候。
(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 在 whereHas 上加入枢轴 table 所以你可以尝试这样的事情:
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