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

时间:2015-05-28 02:46:23

标签: php laravel eloquent laravel-5

我正在使用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');
    }

}

我要完成的是执行查询,该查询仅向我提供与sets相关联的images。基本上加入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 个答案:

答案 0 :(得分:3)

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

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

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

with()方法用于急切加载给定的关系。它没有对检索父记录施加任何限制。您可以阅读更多有关预先加载here的内容。

相关问题