简体   繁体   中英

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.

I want to get the questions referenced from vote's table " question_id ".

Questions Table:

id(PK)| title | description | created_at | updated_at
  • Question Model hasMany votes

    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

    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. 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

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

And you can get all questions from votes like so:

Vote.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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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