【发布时间】:2022-01-20 12:12:49
【问题描述】:
我不确定是否有这样做的方法,但我想在我的查询中将 where 子句添加到第二个 with 但它不起作用。它只是返回所有选票,就好像条件不存在一样。任何帮助将不胜感激。
public function PostId($request)
{
$post_id = $request->post_id;
$user_id = auth('api')->user();
$post = Post::with('categories')
->where('id', $post_id)
->with('votes')
->where('user_id', $user_id->id)
->first();
return $post;
}
【问题讨论】:
-
您只需将它们放入一个数组中。
with(['categories', 'votes']) -
您是要限制关系的急切加载,还是要根据存在关系的条件过滤
Post? -
@Second2None 这不太正确。如果您想为
votes关系添加条件,请使用带有回调的数组:with(['votes' => function ($subQuery) use ($user_id) { return $subQuery->where('user_id', $user_id->id); }])。旁注,$user_id是一个错误的变量名,因为它是实际的User实例,而不仅仅是 id。更改为$user_id = auth('api')->user()->id,或$user = auth('api')->user(),然后更改为$user->id,等等。 -
感谢您的回复。我已经更新了变量名并实现了回调,但它返回了一个空对象。没有错误。
-
只要你最终到达那里......文档参考:laravel.com/docs/8.x/…......祝你好运,玩得开心,享受 Laravel