PHP Laravel 根据投票 Table 的外键从问题 table 中获取所有问题

PHP Laravel get all question from question's table base on the foreign Key of vote's Table

如果可以的话,我希望能够获得所有“已投票的问题”经过身份验证的用户已投票的问题。 return json 格式。

我想获取投票table“question_id”中引用的问题。

问题Table:

id(PK)| title | description | created_at | updated_at

票数Table:

id(PK) | answer_id(FK) | question_id(FK) | user_id(FK)

过滤方法:将return所有已投票的问题与选票一起(我只想要问题)

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);
    }

我能够通过投票模型获得所有 "voted questions"。但我只想得到问题。

当前结果 : 投票问题

 [
    {
        "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",
    }
]

这可能吗?如果没有,任何建议将不胜感激

您可以像这样获得用户的所有投票:

User.php

public function votes()
{
    return $this->hasMany('App\Vote`);
}

您可以像这样从投票中得到所有问题:

Vote.php

public function questions()
{
    return $this->belongsTo('App\Question');
}

那么您应该能够访问所有这些关系,并提取相关值。

$user = Auth::user();
$userVotes = $user->votes()
    ->with('questions')
    ->get()
    ->pluck('question.id', 'question.title');