简体   繁体   中英

Laravel / Eloquent eager loading

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 multiple Tag 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

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

class Question extends Model
{
    public function tags()
    {
        return $this->hasMany('App\Tag');
    }
}

Tag class

class Tag extends Model
{
    public function question()
    {
        return $this->belongsTo('App\Question');
    }
}

And the controller. Instead of all() use get() method.

$questions = Question::with('tags')->get();

As I defined tags method in the Question model. Question::with('tags') should call it. Instead, if you're going to do Question::with('tag') , tag method should be defined in Question model.

Notice the s

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

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