Laravel / Eloquent eager loading

烂漫一生 提交于 2019-12-24 15:49:28

问题


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


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/38688962/laravel-eloquent-eager-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!