首页 > 解决方案 > 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 执行此查询,除非用户经过身份验证?

标签: phplaraveleloquentorm

解决方案


您需要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);

推荐阅读