简体   繁体   中英

Laravel filtering the 'with' results

I'm making a web app which includes a query like the below:

$entry = Entry::with([
    'elements',
    'competition.groups.fields',
    'competition.groups.reviews'
])->find($id);

What I'd like to do is add something along the lines of:

$entry = Entry::with([
    'elements',
    'competition.groups.fields',
    'competition.groups.reviews' -> where('user_id', '=', Auth::user()->id)
])->find($id);

So I'd like to grab the reviews which belong to the entry, where the review's user_id also matches the currently logged in user. Is there a way of doing this?

You can just add a closure for filtering with results:

$entry = Entry::with([
    'elements',
    'competition.groups.fields',
    'competition.groups.reviews' => function($q){
        $q->where('user_id', '=', Auth::id()); // Replaced Auth::user()->id with a shortcut: Auth::id()
    }
])->find($id);

You can try this code too..

$entry = Entry::select('elements', 'competition.groups.fields', 'competition.groups.reviews')->where('user_id', '=', Auth::user()->id)->get();

This code will grab a collection of Entries which belong to the current user who is logged in.

If no entries present Entries collection count will be zero. If some entries exists, then you can loop through the collection and grab entries properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM