带有带数据透视标签的产品我如何访问关系
Product with tags with pivot how can i access relationship
以下 $product returns 产品对象。
但是我怎样才能通过foreach访问relations:array "tags"?
当我执行 $tags->tags 时,我得到了产品的标签 table。
前叉:
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
}
使用 first
而不是 get
来获取模型实例而不是集合。
$product = Product::with('tags')->where('id', $id)->first();
然后你可以遍历每个标签。
foreach ($product->tags as $tag) {
// do something
}
以下 $product returns 产品对象。 但是我怎样才能通过foreach访问relations:array "tags"?
当我执行 $tags->tags 时,我得到了产品的标签 table。
前叉:
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
}
使用 first
而不是 get
来获取模型实例而不是集合。
$product = Product::with('tags')->where('id', $id)->first();
然后你可以遍历每个标签。
foreach ($product->tags as $tag) {
// do something
}