Eloquent nested WHERE statement

家住魔仙堡 提交于 2019-12-23 19:28:38

问题


For an online competition with the goal of photographing certain objects I've got users uploading pictures of objects, where the objects have a category and a subcategory.

A user's dashboard should look something like this:

  ------------------------------------------------ 
  |                Category                      |  
  ------------------------------------------------  
  |   -----------------------------------------  |
  |   | Subcat.          |  Subcat.           |  |
  |   |------------------|--------------------|  |
  |   |Object1 | Object2 | Object1 | Object2  |  |
  |   |------------------|--------------------|  |
  |   |  Pic1  |  Pic1   | Pic1    | Pic1     |  |
  |   |  Pic2  |  Pic2   | Pic2    | Pic2     |  |
  |   ----------------------------------------   |
  |                                              |
  ------------------------------------------------  

In order to be able to output the pictures in the appropriate loop, I installed hasMany relationships between the models. So I can get an object with a convenient hierarchy by

$userPics = Category::with(['subcats','subcats.objects','subcats.objects.pics'])->get();

QUESTION:

For the dashboard of course I only want the images from a certain user: the Pictures model contains a user_id field. I could get the user's pictures directly: Pictures::where('user_id',$user->id)->get();, but then I don't have the structure in the object to create the desired view shown above.

How can I do something like this:

$userPics = Category::with([...])->where('user_id',$user->id)->get();

Many thanks for any tips!


回答1:


You want to get categories with pictures that belong to specified user, so you do this (a bit verbose):

Category::with(['subcats', 'subcats.objects' => function ($q) use ($user) {
        $q->with(['pictures' => function ($q) use ($user) {
            $q->where('user_id', $user->id);
        }]);
    }])
    ->whereHas('subcats', function ($q) use ($user) {
        $q->whereHas('objects', function ($q) use ($user) {
            $q->whereHas('pictures', function ($q) use ($user) {
                $q->where('user_id', $user->id);
            });
        });
    })
    ->get();

You need to use nested with() closures here, because you can load more than two levels of relationship with using dot notation.

If you don't need to load pictures and subcategories data, just remove with() part.

If you also want to filter subcategories, add a closure to with() for subcats.



来源:https://stackoverflow.com/questions/44054999/eloquent-nested-where-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!