【发布时间】:2021-07-15 14:44:37
【问题描述】:
我正在开发一个多公司应用程序,我想根据登录的用户类型过滤数据.. [总部管理员或标准用户]
所以我希望总公司能够看到所有分公司的报告,所以在总公司简介中,我在注册时自动生成了一个代码。因此,所有注册后的分支机构都需要该代码,以便将它们链接到总公司。
这是我得到的错误。
ErrorException
Undefined property: App\Models\User::$company
我想设置一个全局范围,以便总部管理员可以访问分公司,包括数据。
/ 公司模型全球范围/
public static function boot()
{
parent::boot();
if(Auth::user()->user_role_id >= 4 && Auth::user()->access_hq == 'YES'){
static::addGlobalScope('hq_code', function (Builder $builder) {
$builder->where('hq_code', Auth::user()->company['hq_code']);
});
} elseif(Auth::user()->user_role_id >= 4 && Auth::user()->access_hq !== 'YES'){
static::addGlobalScope('id', function (Builder $builder) {
$builder->where('id', Auth::user()->company_id);
});
}
}
/ 模型关系/
/**
* User Model
*/
public function company()
{
return $this->belongsTo(\App\Models\Company::class);
}
/**
* Company Model
*/
public function users()
{
return $this->hasMany(\App\Models\User::class);
}
编辑
如果我以 Admin/HQ Admin 身份登录的查询进行调试,我仍然会收到错误,但是当我以分支用户/标准用户身份登录时,我会收到此错误
Illuminate\Database\Eloquent\Builder {#1955 ▼
#query: Illuminate\Database\Query\Builder {#1962 ▶}
#model: App\Models\Company {#1948 ▶}
#eagerLoad: []
#localMacros: array:4 [▶]
#onDelete: Closure(Builder $builder) {#1944 ▶}
#passthru: array:19 [▶]
#scopes: array:2 [▼
"Illuminate\Database\Eloquent\SoftDeletingScope" => Illuminate\Database\Eloquent\SoftDeletingScope {#1765 …}
"id" => Closure(Builder $builder) {#1854 ▼
class: "App\Models\Company"
file: "DRIVE:\webapp\app\Models\Company.php"
line: "70 to 72"
}
]
#removedScopes: []
}
编辑 - dd(auth()->user())
App\Models\User {#1938 ▼
#fillable: array:4 [▶]
#hidden: array:2 [▶]
#attributes: array:17 [▶]
#connection: "mysql"
#table: "users"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#original: array:17 [▶]
#changes: []
#casts: array:1 [▶]
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
#forceDeleting: false
}
【问题讨论】:
-
这一行是否给您带来了错误?
$builder->where('hq_code', Auth::user()->company['hq_code']);你调试了吗 -
是的,它抛出了一个错误,我确实调试了它,当我以 HQ Admin 身份登录时它仍然给我同样的错误,但如果我以标准用户或分支用户身份登录,我会过滤数据
-
我认为这是因为
Auth::user()->company在调用Company时需要启动Company但由于我们在in中尚未启动> 靴子。有意义吗? -
所以它试图启动公司模型,同时试图过滤未启动的公司模型??
-
我不确定您所说的 token 是什么意思,但如果我们彼此理解正确,那就是这个。更准确地说;在
addGlobalScope中添加的范围将在我们加载任何关系->company之前播放。这意味着属性$company还不存在。不过我没有解决你的问题。
标签: laravel