[英]PHP Laravel get all question from question's table base on the foreign Key of vote's Table
如果可以的話,我希望能夠獲得所有“已投票的問題”,即經過身份驗證的用戶投票的問題。 並以 json 格式返回。
我想從投票表“ question_id ”中獲取引用的問題。
問題表:
id(PK)| title | description | created_at | updated_at
問題 Model 有很多票
class Question extends Model { public function votes() { return $this->hasMany(Vote::class, 'question_id'); } }
投票表:
id(PK) | answer_id(FK) | question_id(FK) | user_id(FK)
投票 Model屬於一個問題
class Vote extends Model { public function question() { return $this->belongsTo(Question::class, 'question_id'); } }
過濾方法:將所有投票的問題與投票一起返回(我只想要問題)
public function filtered()
{
$user_id = Auth::user()->id;
$votes = Vote::with('question')->where('user_id', $user_id)->get();
$votes->makeVisible('question');
return response()->json($votes);
}
我能夠通過投票 Model 獲得所有“投票的問題”。 但我只想問這個問題。
當前結果:有投票問題的投票
[
{
"id": 1,
"question_id": 1,
"answer_id": 2,
"user_id": 1,
"question": {
"id": 1,
"title": "a question this user voted",
}
},
{
"id": 2,
"question_id": 2,
"answer_id": 3,
"user_id": 1,
"question": {
"id": 2,
"title": "another question this user voted",
}
}
]
期望的結果:僅投票的問題
[
{
"id": 1,
"title": "a question this user voted",
},
{
"id": 2,
"title": "another question this user voted",
}
]
這可能嗎? 如果沒有,任何建議將不勝感激
您可以像這樣獲得用戶的所有選票:
用戶.php
public function votes()
{
return $this->hasMany('App\Vote`);
}
你可以從投票中得到所有問題,如下所示:
投票。php
public function questions()
{
return $this->belongsTo('App\Question');
}
然后您應該能夠訪問所有這些關系,並提取相關值。
$user = Auth::user();
$userVotes = $user->votes()
->with('questions')
->get()
->pluck('question.id', 'question.title');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.