简体   繁体   English

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

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

If I can I would like to be able to get all " voted questions " the questions authenticated user have voted .如果可以的话,我希望能够获得所有“已投票的问题”,即经过身份验证的用户投票的问题。 and return in a json format.并以 json 格式返回。

I want to get the questions referenced from vote's table " question_id ".我想从投票表“ question_id ”中获取引用的问题。

Questions Table:问题表:

id(PK)| title | description | created_at | updated_at
  • Question Model hasMany votes问题 Model 有很多

    class Question extends Model { public function votes() { return $this->hasMany(Vote::class, 'question_id'); } }

Votes Table:投票表:

id(PK) | answer_id(FK) | question_id(FK) | user_id(FK)
  • Vote Model belongsTo a question投票 Model属于一个问题

    class Vote extends Model { public function question() { return $this->belongsTo(Question::class, 'question_id'); } }

Filter Method : Will return all the voted question alongside the votes (I only want the questions)过滤方法:将所有投票的问题与投票一起返回(我只想要问题)

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

I was able to get all the "voted questions" through Vote Model.我能够通过投票 Model 获得所有“投票的问题”。 but I would like to get only the question.但我只想问这个问题。

Current Result : votes with 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",
        }
    }
]

Desired Result : only voted questions期望的结果:仅投票的问题

 [
     {
       "id": 1,
       "title": "a question this user voted",
     },
     {
       "id": 2,
       "title": "another question this user voted",
    }
]

is this possible?这可能吗? if not, any advice will be appreciated如果没有,任何建议将不胜感激

You can get all votes for a user like so:您可以像这样获得用户的所有选票:

User.php用户.php

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

And you can get all questions from votes like so:你可以从投票中得到所有问题,如下所示:

Vote.php投票。php

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

Then you should be able to access all these relationships, and pluck the relevant values.然后您应该能够访问所有这些关系,并提取相关值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM