Laravel belongsToMany() 与 all() 或 where() 方法的关系,而不仅仅是 find()

Laravel belongsToMany() relation to work with all() or where() method and not just find()

我有一个名为 Images 的模型 我有另一个名为 Categories

的模型

一张图片可以有很多类别,一个类别也可以有很多图片。它们是由image_categorytable连接的,我在Laravel的Eloquent.

做了模型

现在,我想获取图像的所有类别,我在 Image.php 模型中执行此操作:

function categories()
{
  return $this->belongsToMany("Category", "image_category");
}

现在我希望以下方法之一起作用:

Image::categories()->get()->toArray();

或:

Image:all()->categories()->get()->toArray();

上面的方法不起作用,我看到了 Laravel 的文档,我看到所有的例子都是通过方法 find() 给出的:

Images:find(1)->categories()->get()->toArray();

我的问题:我应该如何将关系 categories() 与方法 all()where().

一起使用

我可以直接在SQL中写查询,但我想使用Eloquent的功能。

如果您希望所有带有 categories 的图像嵌套在结果中,您应该使用预先加载:

$images = Image::with('categories')->get();

或者:

$images = Image::where('foo', 'bar')->with('categories')->get();