I'm not sure if there's a a way of doing this but I would like to add a where clause to the second with in my query but it doesn't work. It just returns all the votes as if the condition wasn't there. Any help would be appreciated.
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;
}
CodePudding user response:
You need to use closure in your with
statement.
Also, I'd recommend using findOrFail()
instead of where
conditional for your query. Therefore, in case you pass a wrong post_id
in your request an exception 404 will be thrown.
A nicer way to accomplish what you want could be:
public function PostId($request)
{
$post = Post::with(['categories', 'votes' => function($query){
$query->where('user_id', auth('api')->user()->id);
})
->findOrFail($request->post_id);
return $post;
}
CodePudding user response:
$post = Post::find($post_id) // Find method will return only first record. no need to call ->first() explicitly.
->with([
'categories',
'votes'
])
For the ->where('user_id', $user_id->id)
, you dont need to do it in here as you already have defined the relation 'votes'.
Class Post
{
public function votes()
{
return $this->hasMany(Vote::class)->where('user_id', $this->user_id); // You can have the where condition here assuming you have user id field present in the Post model. Else you can keep it as below in your query
}
}
With user id in the runtime query
$post = Post::find($post_id)
->with([
'categories',
'votes' => function($query) use($user_id) {
$query->where('user_id', $user_id->id);
}
])