2015-01-20 133 views
2

我想創建一個單頁的應用程序與AngularJS作爲我的前端和Laravel作爲我的後端。嘗試創建需要訪問與另一個模型的關係的表時遇到問題。Laravel - 訪問與AngularJS的關係模型

對於這個例子,假設我有一個顯示產品的表格。每個產品也會有一個品牌。

隨着Laravel的刀片語法,我會通過解決這個問題:

<table class="table table-bordered"> 
    <tr> 
    <th>Name</th> 
    <th>Brand</th> 
    </tr> 
    @foreach($products as $product) 
    <tr> 
    <td>{{ $product->name }}</td> 
    <td>{{ $product->brand->name }}</td> 
    </tr> 
    @endforeach 
    <!-- End of product entry for {{ $product.name }} --> 
</table> 

具有角,我希望我能做到這一點:

<table class="table table-bordered"> 
    <tr> 
    <th>Name</th> 
    <th>Brand Id</th> 
    </tr> 
    <tr ng-repeat="product in products"> 
     <td>@{{ product.name }}</td> 
     <td>@{{ product.brand.name }}</td> 
    </tr> 
    <!-- End of product entry for @{{ product.name }} --> 
</table> 

不幸的是,@ {{product.brand。 name}}不起作用,並且看起來並不是訪問父關係的簡單方法。

僅供參考,我的控制器看起來是這樣的:

app.controller('CtrlProducts', function($scope, $http){ 

    $scope.products = []; 

    $http.get('/api/products'). 
    success(function(data, status, headers, config) { 
     angular.forEach(data, function(product){ 
     $scope.products.push(product); 
     }); 
    }). 
    error(function(data, status, headers, config) { 
     console.log(data); 
    }); 
}); 

,我能想到的唯一的解決辦法是讓一個單獨的API調用的品牌模型和數據存儲到一個地圖對象。然後我可以打電話:@ {{brandMap.get(product.brand_id)}}

有誰知道更簡單的解決方案嗎?看起來這將是一個普遍的問題。

謝謝。

回答

2

當你Laravel後端獲取的產品不只是使用

Product::find($id); 

而是

Product::with('brand')->find($id); 

你去那裏:)相應的文檔部分:http://laravel.com/docs/4.2/eloquent#eager-loading

+0

這正是我需要!謝謝 – 2015-01-20 21:46:04

+0

我會感激upvote和複選標記;) – 2015-01-20 21:48:01

+0

我會,但需要15聲望。給我一個upvote,我可能會! ;) – 2015-01-20 21:55:49