A.B.Developer A.B.Developer - 4 months ago 9
PHP Question

eager load of relations of a specific model in laravel

I have a model named

Test
like this:

class Test extends Model
{
public $primaryKey = 'test_id';
public function questions ()
{
return $this->belongsToMany('App\Question', 'question_test', 'test_id', 'question_id');
}
}


And a
Question
model like this:

class Question extends Model
{
public function tests ()
{
return $this->belongsToMany('App\Test', 'question_test', 'question_id', 'test_id');
}
}


As you see there is a
ManyToMany
relation between this two model.

Now in a controller function, I want to get an specific Test(by id) and send it to a view. then eager load all it's
questions
related models and send it to another view. like this :

public function beginTest ($course_id, $lesson_id, $test_id)
{

$test = Test::find($test_id);


if ($test->onebyone) {

return view('main/pages/test/test-onebyone', compact('test'));

} else {

$test = $test->with('questions.options')->get();
return view('main/pages/test/test-onepage', compact('test', 'done_test_id'));

}
}
}


Problem is that when I use
with()
laravel method to eager load relations, it return all Test models with their
Question
relations while I want to get relations of selected
Test
model only.

what is your solution to solve that?

Answer

You can use 'lazy eager loading'.

$test->load('questions.options');

Using with off the model instance will make it use a new builder and cause a new query to be executed.

Comments