表格结构如下所示:
person
id - integer
name - string
company
id - integer
name - string
person_company
person_id - integer
company_id - integer
这是模型:
class Person extends Model
{
public function companies()
{
return $this->belongsToMany('App\Company', 'person_company');
}
}
class Company extends Model
{
public function persons()
{
return $this->belongsToMany('App\Person', 'person_company');
}
}
这意味着一个人可以是多个公司的一部分,每个公司可以有很多人;
在标准 Laravel
users 表上,我们有:
users
id - integer
name - string
company_id - integer
每个用户都属于一个公司。
[问题 1]
如何创建一个范围以仅包含属于特定公司的人员?
我尝试使用GlobalScope:
class CompanyScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$model->companies()->where('company_id', 1);
}
}
class CompanyScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$query->companies()->where('company_id', 1);
}
}
但无法通过...我也尝试了LocalScopes:
public function scopeCo($query, $company_id)
{
return $query->companies()->where('company_id', $company_id);
}
没有成功...
[问题 2]
另一件事需要指出的是,可以选择将变量发送到上述本地范围示例代码中的范围,其中接收company_id
($company_id) 从用户通过 Controller
,使用Auth::user()->company_id;
。
我希望在 Controller 上使用的是我的本地范围将返回链接到用户公司的人员,截至:
Person::Co(Auth::user()->company_id)->get();
有人实现过这种范围吗?
谢谢!
最佳答案
您可以使用whereHas
查询相关表。
public function scopeCo($query, $company_id)
{
$query->whereHas('companies', function ($query) use ($company_id) {
$query->where('person_company.company_id', $company_id);
});
}
Person::Co(Auth::user()->company_id)->get();
关于php - 如何在 Laravel 5.4 中的 *belongsToMany* 表连接上创建作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43848347/