This will be an easy question for some, but I can't seem to find the answer online or in the documentation (only variants of it which I don't want).
- Lets say we have a
Question
class - Each
Question
object can optionally have multipleTag
s
I have set the classes up and things behave as expected. Currently I use:
$questions = Question::all();
This works as expected, however it does not eager load.
To be clear: $question->tags
gives the array I am expecting. There is not a relationship problem.
Due to new requirements I will be creating a view with possibly thousands of questions, so this eager loading is a must.
I attempted to use:
$questions = Question::with('tag')->all();
Which gives error message:
BadMethodCallException in Builder.php line 2345: Call to undefined method Illuminate\Database\Query\Builder::all()
Every tutorial, or way I google eager loading, either specifies an ID, OR is a tutorial on how to ONLY show parents with children.
I simple want "all and their children".
This has got to be easy.. does anyone know how to do it?
Thanks Rick
I've marked both answers as correct: the original syntax suggested is correct, and the class name issue raised was the final issue. Thanks all:
$questions = Question::with('tags')->get();
You should define the method in your model. As far as I see you're going to have one to many relationship. And that's going to be
Tag class
And the controller. Instead of
all()
useget()
method.As I defined
tags
method in theQuestion
model.Question::with('tags')
should call it. Instead, if you're going to doQuestion::with('tag')
,tag
method should be defined inQuestion
model.Notice the s