2016-04-14 25 views
0

我試圖做的是在嵌套的ng-repeat中獲得雄辯關係的最深層次結構的屬性。Angularjs + Laravel:在嵌套的ng-repeat中獲取雄辯關係的屬性

這是關係。

Order ..hasMany.. SubItems ..belongTo.. Product

有一個模型Order,其hasMany模型SubItemsSubItems型號belongsTo型號Product

我有一個Order的數組,我想從Order的每個對象訪問相關的Productng-repeat

<table> 
     <tbody ng-repeat="order in tc.orders" >//I use "as" syntax, so I use "tc."here 
      <tr ng-click="tc.showOrderDetail(order.id)"> 
       <td ng-bind="order.id"></td> 
       <!-- "order.id" works in both lines --> 
      </tr> 
       <tr ng-repeat="subItem in order.subItems"> 
        <td ng-bind="subItem.price"></td> 
        <!-- This "subItem.price" appears --> 
        <td ng-bind="subItem.product.name"></td> 
        <!-- This "subItem.product.name" doesn't appear --> 
       </tr> 
     </tbody> 
    </table> 

的關係(SubItems)的第二級可以通過將一個.進行訪問,但顯然我需要用不同的方式來訪問第三級(Product)。

如果您提供任何建議,我將不勝感激。

信息

當我使用Laravel的foreach循環,這可以通過...訪問

{{$subItem->product->name}} //This works fine!

控制器的方法是...

public function getOrders() 
{ 
    $orders = $this->order->with('customer', 'subitems')->orderBy('id', 'desc')->get(); 
    return $orders; 
} 
+0

請包含您的控制器代碼。 'product'一定不能加載到你的'subItem'模型上,所以我們需要看你的控制器以幫助 – Jeff

+0

謝謝Jeff。我添加了它。相信與否,當我使用Laravel的forloop時,沒有錯誤,而'product'與'subitem'有關。 – Hiroki

+1

當你調用'$ subItem-> product'時,它會自動爲你加載它。如果您希望它以JSON格式顯示,您必須手動加載它 – Jeff

回答

1

在您的代碼中,您不會告訴Laravel急於將項目模型添加到您的子項模式中湖您需要添加產品預先加載像這樣:

$this->order->with('customer', 'subitems.product')->orderBy('id', 'desc')->get(); 

和訪問它像任何其他JavaScript對象subItem.product.name

它Laravel foreach循環爲你工作的原因是因爲當你請求像的關係屬性Laravel即$subItem->product而不是作爲一種方法,Laravel會自動將關係Eloquent對象實例化到Model對象中。

+0

非常感謝。我想再問一個問題......在閱讀文檔後,我認爲在Laravel的模型之間放置一個點('.')並不是常見做法。在控制器中指出Eloquent關係時,這樣做是否很常見?或者,你是如何找到它的? – Hiroki

+1

https://laravel.com/docs/master/eloquent-relationships#eager-loading 向下滾動到Nested Eager Loading – Cptmaxon