[英]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.