Laravel/雄辩的渴望加载 [英] Laravel / Eloquent eager loading

查看:68
本文介绍了Laravel/雄辩的渴望加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于某些人来说,这将是一个简单的问题,但我似乎无法在网上或文档中找到答案(只是我不想要的变体).

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).

  • 让我们说我们有一个Question
  • 每个Question对象可以选择具有多个Tag s
  • 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.

要清楚:$question->tags给出了我期望的数组.没有关系问题.

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.

我尝试使用:

  • $questions = Question::with('tag')->all();

哪个给出错误消息:

Builder.php第2345行中的BadMethodCallException:调用未定义的方法Illuminate \ Database \ Query \ Builder :: all()

BadMethodCallException in Builder.php line 2345: Call to undefined method Illuminate\Database\Query\Builder::all()

每个教程,或者我用谷歌渴望加载的方式,要么指定一个ID,要么是一个关于如何仅显示带孩子的父母的教程.

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?

谢谢 里克

推荐答案

您应该在模型中定义方法.据我所知,您将有一对多的关系.这将是

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');
    }
}

标记类

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

还有控制器.代替all(),请使用get()方法.

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

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

正如我在Question模型中定义的tags方法一样. Question::with('tags')应该调用它.相反,如果要执行Question::with('tag'),则应在Question模型中定义tag方法.

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.

注意 s

这篇关于Laravel/雄辩的渴望加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆