O
O
Oleg Timoshenko2015-10-13 21:09:10
Laravel
Oleg Timoshenko, 2015-10-13 21:09:10

How to get data across multiple tables?

There are tables questions, tags, question_tags, answers.
They are connected like this:

// App\Models\Question

public function tags()
{
  return $this->belongsToMany('App\Models\Tag', 'question_tags');
}

public function answers()
{
  return $this->hasMany('App\Models\Answer');
}

// App\Models\Answer

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

// App\Models\Tag

public function questions()
{
  return $this->belongsToMany('App\Models\Question', 'question_tags');        
}

Actually the question is how to get all the answers to the questions of a particular tag
// App\Models\Tag

public function answers()
{
  return ???        
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Evgrafovich, 2015-10-14
@gultaj

write directly in the controller or repository, where you get the results there $tag = Tag::with(['questions.answers'])->where('id', $id)->first();
So get an object containing a collection of questions with the questions method, I can't say for sure, but it looks like the pluck method will collect all the answers:
$answers = $tag->questions->pluck('answers');
If it doesn't collect, organize a foreach loop (as a last resort) or read more about Laravel's collections.

D
D', 2015-10-13
@Denormalization

Here you need to use laravel.com/docs/5.1/eloquent-relationships#has-ma...

// App\Models\Tag

public function answers()
{
    return $this->hasManyThrough('App\Models\Answer', 'App\Models\Question');
}

I think that will work. No way to check now.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question