【发布时间】:2015-05-28 02:46:23
【问题描述】:
我正在使用 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');
}
}
我想要完成的是执行一个查询,该查询只给我与images 关联的sets。本质上加入sets 和image_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() 应该这样工作吗?
【问题讨论】:
-
你的班级是
Images,所以在你的关系中它应该是return $this->belongsToMany('App\Images'); -
打错字了,我会改正的。实际的类称为“图像”
-
哦,好吧。请粘贴您的代码以避免拼写错误:)
标签: php laravel eloquent laravel-5