php - laravel 仅为“auth”用户加载特定关系
问题描述
当用户通过身份验证时,有没有机会让 laravel 只加载特定的项目?
假设这段代码:
public function getCategory(Category $category){
$items = $category->products()->with(['otherRelation', 'favouriteUsers' => function($query){
$query->where('user_id', Auth::id())->select(['product_id', 'user_id']);
}])->withCount([
'views',
])->latest()->paginate(20);
在加载关系的那一刻favouriteUsers
,无论用户是否经过身份验证,有什么方法可以阻止 laravel 执行此查询,除非用户经过身份验证?
解决方案
您需要favoriteProducts()
在User::class
这样会更容易获得
$user = Auth::user();
$favoriteProducts = $user->favoriteProducts()
->with('otherRelation')
->withCount('views')
->whereHas('category', function($categoryQB) use($category) {
$categoryQB->where('id', $category->id);
})
->latest()->paginate(20);
推荐阅读
- html - 使用 mix-blend-mode 从其父级中剔除一个形状,同时保持同级文本正常
- javascript - 如何将“CLEAR”按钮添加到 IonDateTime?
- python - 从阈值蒙版生成圆形粒子的分割蒙版?
- c++ - 如何将字符串映射到对象成员?
- haskell - 评估部分应用的功能
- append - 如何使用通用模式在 Nuxt 中附加 html
- json - Pandas read_json - 停止将索引转换为日期时间
- facebook - 如何将 Messenger 数据提取到我自己的数据库中?
- python - 更改函数的返回值会影响不应受到影响的元素
- firebase - 如何向 Firestore 验证 Firebase 功能/管理员请求