我有一個允許多個用戶的應用程序。每個用戶之間完全隔離;這意味著數據庫中所有非用戶的內容都有一個user_id列,并且只有登錄用戶才可以查看、更新或刪除它們。此外,用戶不能使用其他人的 user_id 創(chuàng)建行。有沒有內置的方法可以用 Lumen/Lighthouse 來解決這個問題?這是我所做的,它有效,但我想知道我是否重新發(fā)明了輪子:每個模型都有一個user關系,如下所示:public function user(): BelongsTo{ return $this->belongsTo(User::class);}我在這些模型中添加了一個HasOwnerTrait,其中包含以下內容:public static function boot(){ parent::boot(); static::creating(function (Model $model) { $model->user_id = Auth::user()->id; }); static::saving(function (Model $model) { if ($model->user_id !== Auth::user()->id) { $exception = new ModelNotFoundException(); $exception->setModel(self::class, $model->id); throw $exception; } }); static::deleting(function (Model $model) { if ($model->user_id !== Auth::user()->id) { $exception = new ModelNotFoundException(); $exception->setModel(self::class, $model->id); throw $exception; } });}public function scopeIsOwner($query){ return $query->where('user_id', Auth::user()->id);}最后,在我的模式定義中:type Query { recipes: [Recipe!]! @all(scopes: ["isOwner"])}type Mutation { createRecipe(input: CreateRecipeInput! @spread): Recipe @create updateRecipe(id: ID!, input: UpdateRecipeInput! @spread): Recipe @update deleteRecipe(id: ID!): Recipe @delete}同樣,這是可行的,但是是否需要像這樣臨時使用,或者是否有更好的方法?
1 回答

拉風的咖菲貓
TA貢獻1995條經驗 獲得超2個贊
我認為你的解決方案很好,它節(jié)省了編寫一大堆樣板文件。一些小建議:
boot
您可以將方法重命名為 ,從而使您的特征成為可引導特征,由框架自動調用bootHasOwnerTrait
。
也許可以考慮isOwner
默認將作用域設置為活動狀態(tài)。在 Laravel 中,這被容易混淆地稱為全局作用域。這允許您省略顯式命名范圍,但如果您有一些不應應用的查詢(例如統計信息),您仍然可以省略它。
- 1 回答
- 0 關注
- 161 瀏覽
添加回答
舉報
0/150
提交
取消