Laravel / Eloquent eager loading

2019-07-25 21:32发布

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 Tags

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

2条回答
Rolldiameter
2楼-- · 2019-07-25 21:42

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

查看更多
我想做一个坏孩纸
3楼-- · 2019-07-25 22:00

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

查看更多
登录 后发表回答