以下$ product返回Product对象。 但是如何通过foreach访问关系:array“tags”?
当我执行$ tags->标签时,我会获得产品表的标签。
FOREACH:
foreach ($product as $tags) {
}
实例:
$product = Product::with('tags')->where('id',$id)->get();
输出:
Product {#371 ▼
#table: "products"
#connection: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:10 [▶]
#original: array:10 [▶]
#relations: array:1 [▼
"tags" => Collection {#399 ▼
#items: array:2 [▼
0 => Tag {#397 ▼
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:4 [▶]
#original: array:6 [▶]
#relations: array:1 [▶]
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
答案 0 :(得分:2)
使用first
代替get
来获取模型实例而不是集合。
$product = Product::with('tags')->where('id', $id)->first();
然后你可以遍历每个标签。
foreach ($product->tags as $tag) {
// do something
}