[英]Laravel Eloquent many to many using with() returning empty array
我正在使用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 |
+----+----------------+
我在照片中創建了一個AboutToMany關系,並設置了將這兩者鏈接在一起的模型。
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
。 本質image_set
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()
應該以這種方式工作嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.