我不確定是否有這樣做的方法,但我想在我的查詢中向第二個添加一個 where 子句,但它不起作用。它只是回傳所有選票,就好像條件不存在一樣。任何幫助,將不勝感激。
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;
}
uj5u.com熱心網友回復:
您需要在with陳述句中使用閉包。
另外,我建議您使用findOrFail()而不是where有條件的查詢。因此,如果您post_id在請求中傳遞錯誤,將拋出例外 404。
完成您想要的更好的方法可能是:
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;
}
uj5u.com熱心網友回復:
$post = Post::find($post_id) // Find method will return only first record. no need to call ->first() explicitly.
->with([
'categories',
'votes'
])
對于->where('user_id', $user_id->id),您不需要在此處執行此操作,因為您已經定義了關系“投票”。
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
}
}
在運行時查詢中使用用戶 ID
$post = Post::find($post_id)
->with([
'categories',
'votes' => function($query) use($user_id) {
$query->where('user_id', $user_id->id);
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/384979.html
