【发布时间】:2019-07-25 14:04:47
【问题描述】:
我在现有的 Laravel 安装中设置了用户和代理之间的多对多数据库关系。
在前端,我使用下拉过滤器将agency_id 发送到应该通过此agency_id 变量过滤/返回所有用户的服务器。
在我的模型中: 用户.php
/**
* The agencies that belong to the user.
*/
public function agencies()
{
return $this->belongsToMany('App\Agency');
}
Agency.php
/**
* The users that belong to the agency.
*/
public function users()
{
return $this->belongsToMany('App\User');
}
当我查询数据库时,我检查代理参数是否存在于标题中
->when($request->agency, function ($q) use ($request, $schema) {
// Determine whether agency_id foreign key exists or if it's a pivot relationship
if(Schema::hasColumn($schema, 'agency_id'))
{
return $this
->repository
->whereAgency($q, \Hashids::decode($request->agency)[0]);
}
else
{
return $this
->repository
->whereAgencyPivot($q, \Hashids::decode($request->agency)[0]);
}
})
在存储库中,我执行以下操作:
public function whereAgencyPivot($q, string $agency)
{
return $q->wherePivot('agency_id', $agency);
}
这会返回以下错误:
找不到列:1054 'where 子句'中的未知列'pivot'
我也试过了:
public function whereAgencyPivot($q, string $agency)
{
return $q->agencies()->where('agency_user.agency_id', $agency);
}
返回:
调用未定义的
method Illuminate\Database\Eloquent\Builder::agencies()
我有什么遗漏的吗?
【问题讨论】:
标签: php mysql laravel laravel-5 eloquent