Laravel使用whereHas進行過濾不符合條件的預加載with數據


問題描述:目前有用戶表,文章表,文章評論表,收藏表。我需要獲我的收藏文章列表(可以被搜索,通過分類,文章標題等),通過收藏預加載with文章表,文章評論表,文章用戶表

解決辦法:通過whereHas限定要查詢的文章字段條件,然后進行預加載with獲取數據

案例:

// 獲取自己的收藏
    public function my(Request $request)
    {
        $limit  = $request->input('limit');
        $deviceRegionList = UserModel::where('token', $this->user_token())->firstOrFail()->article_collection()->whereHas('article', function($query){
            $request = request();
            $article_class_id  = $request->article_class_id;
            if(!empty($article_class_id)){
                $query->where('article_class_id', intval($article_class_id));
            }
            // 狀態
            $status = $request->status;
            if(!empty($status)){
                $query->where('status', intval($status));
            }
            // 作物
            $crop_class_id = $request->crop_class_id;
            if(!empty($crop_class_id)){
                $query->where('crop_class_id', intval($crop_class_id));
            }
            // 標題
            $title = $request->title;
            if(!empty($title)){
                $query->where('title', 'like', '%'.$title.'%');
            }
        })->with('article', 'article.user', 'article.article_class', 'article.crop_class')->orderBy('id','desc')->paginate($limit)->toArray();
        $returnData = [];
        $returnData['msg']              = "查詢成功";
        $returnData['count']            = $deviceRegionList['total'];
        $returnData['current_page']     = $deviceRegionList['current_page'];
        $returnData['data']             = $deviceRegionList['data'];
        return success($returnData);
    }

Laravel文檔:

// 轉自:https://laravelacademy.org/post/19533.html 查詢存在的關聯關系 訪問一個模型的記錄的時候,你可能希望基於關聯關系是否存在來限制查詢結果的數目。例如,假設你想要獲取所有至少有一個評論的博客文章,要實現這個功能,可以傳遞關聯關系的名稱到 has 和 orHas 方法: // 獲取所有至少有一條評論的文章... $posts = App\Post::has('comments')->get(); 你還可以指定操作符和數目來自定義查詢: // 獲取所有至少有三條評論的文章... $posts = Post::has('comments', '>=', 3)->get(); 還可以使用”.“來構造嵌套 has 語句,例如,你要獲取所有至少有一條評論及投票的文章: // 獲取所有至少有一條評論獲得投票的文章... $posts = Post::has('comments.votes')->get(); 如果你需要更強大的功能,可以使用 whereHas 和 orWhereHas 方法將「where」條件放到 has 查詢上,這些方法允許你添加自定義條件約束到關聯關系條件約束,例如檢查一條評論的內容: use Illuminate\Database\Eloquent\Builder; // Retrieve posts with at least one comment containing words like foo%... $posts = App\Post::whereHas('comments', function ($query) { $query->where('content', 'like', 'foo%'); })->get(); // Retrieve posts with at least ten comments containing words like foo%... $posts = App\Post::whereHas('comments', function ($query) { $query->where('content', 'like', 'foo%'); }, '>=', 10)->get();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM