【发布时间】:2021-09-07 01:09:13
【问题描述】:
当用户通过身份验证时,是否有机会让 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 执行此查询,除非用户经过身份验证?
【问题讨论】:
-
尝试 $items = $category->products()->with(['otherRelation'])->when(Auth::id(),function($query){ $query-> whereHas('favouriteUsers' , function($query){ $query->where('user_id', Auth::id())->select(['product_id', 'user_id']); }); }) - >withCount([ 'views', ])->latest()->paginate(20);
-
我认为不是
whereHas而是with,不是吗? -
如果你需要数据那么你可以使用 with 否则 wherehas.wherehas 不会返回 favouriteUsers 的结果。所以如果你正在寻找数据然后使用 with
-
如果您有任何问题,请告诉我