我正在制作一个包含如下查询的Web应用程序:
$entry = Entry::with([
'elements',
'competition.groups.fields',
'competition.groups.reviews'
])->find($id);
我想做的是添加一些类似以下内容的内容:
$entry = Entry::with([
'elements',
'competition.groups.fields',
'competition.groups.reviews' -> where('user_id', '=', Auth::user()->id)
])->find($id);
因此,我想获取属于该条目的评论,其中评论的user_id也与当前登录的用户匹配。有没有办法做到这一点?
您可以添加一个闭包来过滤with
结果:
$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);
你也可以试试这段代码。
$entry = Entry::select('elements', 'competition.groups.fields', 'competition.groups.reviews')->where('user_id', '=', Auth::user()->id)->get();
此代码将获取属于当前登录用户的Entries
集合。
如果不存在任何条目Entries
则集合计数将为零。如果存在某些条目,则可以循环访问集合并抓取条目属性。