2017-05-29 71 views
1

以下$ product返回产品对象。 但我怎么可以通过foreach访问关系:数组“标签”?产品带有标签,带标签如何访问关系

当我做$标签 - >标签我得到产品表的标签。

的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 
    } 

回答

2

使用first而不是get得到一个模型实例,而不是收藏。

$product = Product::with('tags')->where('id', $id)->first(); 

然后你可以遍历每个标签。

foreach ($product->tags as $tag) { 
    // do something 
} 
+0

Ahaaa,谢谢,工作! – Bas