首页 文章

Laravel Eloquent使用with()返回空数组

提问于
浏览
0

我正在使用Laravel 5和Eloquent并且具有多对多关系设置,如下所示

images
+----+---------------+------------------+
| id |  image_name   |  image_location  |
+----+---------------+------------------+
|  1 | kittens.jpg   | C:\kittens.jpg   |
|  2 | puppies.jpg   | C:\puppies.jpg   |
|  3 | airplanes.jpg | C:\airplanes.jpg |
|  4 | trains.jpg    | C:\trains.jpg    |
+----+---------------+------------------+

image_set (pivot table)
+------------+----------+
| set_id     | image_id |
+------------+----------+
|          1 |        1 |
|          1 |        2 |
|          2 |        3 |
|          2 |        4 |
+------------+----------+

sets
+----+----------------+
| id |  description   |
+----+----------------+
|  1 | cute animals   |
|  2 | transportation |
|  3 | food           |
+----+----------------+

我在照片中创建了一个belongsToMany关系,并设置模型将这两者联系在一起 .

class Image extends Model {

    public function sets()
    {
        return $this->belongsToMany('App\Set');
    }
}

class Set extends Model {

    public function images()
    {
        return $this->belongsToMany('App\Image');
    }

}

我想要完成的是执行一个查询,它只给我 setsimages 相关联 . 基本上加入 setsimage_set 表只返回 1,2 的集合

我目前有一个相当长的查询工作...

$availSets = Set::join('image_set','image_set.set_id','=','sets.id')
        ->groupBy('sets.id')
        ->get();

但我已经看到很多例子,这也应该有效 .

$availSets = Set::with('images')->get();

然而,它返回所有3组,包括没有相关图像的那些 .

#relations: array:1 [▼
    "images" => Collection {#179 ▼
      #items: []
    }
  ]

我错误地使用了这个吗? with() 应该以这种方式工作吗?

1 回答

  • 3

    您正在寻找 has() 方法,而不是 with() 方法:

    $availSets = Set::has('images')->get();
    

    这将返回至少包含一个图像的所有集合 . 可以在here找到相关文档 .

    with() 方法用于急切加载给定的关系 . 它没有对检索父记录施加任何限制 . 您可以在eager loading here上阅读更多信息 .

相关问题