LaravelはwhereHasを使用して条件に合わないプリロードwithデータをフィルタリングする
7406 ワード
質問説明:現在、ユーザーテーブル、文章テーブル、文章コメントテーブル、コレクションテーブルがあります.私のコレクションの文章リスト(検索可能、分類、文章タイトルなど)を取得し、コレクションを通じてwith文章表、文章評論表、文章ユーザー表を事前にロードする必要があります.
解決策:whereHasでクエリーする記事フィールドの条件を定義し、事前ロードwithでデータを取得します.
ケース:
Laravelドキュメント:
転載先:https://www.cnblogs.com/xiaqiuchu/p/11508426.html
解決策: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();
転載先:https://www.cnblogs.com/xiaqiuchu/p/11508426.html