【问题标题】:Laravel - accessing relationship Models with AngularJSLaravel - 使用 AngularJS 访问关系模型
【发布时间】:2015-01-20 21:34:51
【问题描述】:

我正在尝试使用 AngularJS 作为我的前端和 Laravel 作为我的后端来创建一个单页应用程序。我在尝试创建需要访问与另一个模型的关系的表时遇到了问题。

对于此示例,假设我有一个显示产品的表格。每个产品也会有一个品牌。

使用 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>

使用 Angular,我希望我能做到这一点:

<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);
    });
});

我能想到的唯一解决方案是对 Brand 模型进行单独的 api 调用并将数据存储到地图对象中。然后我可以打电话:@{{ brandMap.get(product.brand_id) }}

有人知道更简单的解决方案吗?似乎这将是一个常见的问题。

谢谢。

【问题讨论】:

    标签: angularjs laravel


    【解决方案1】:

    在你的 Laravel 后端获取产品时,不要只使用

    Product::find($id);
    

    而是

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

    你去 :) 相应的文档部分:http://laravel.com/docs/4.2/eloquent#eager-loading

    【讨论】:

    • 这正是我所需要的!谢谢你
    • 我愿意,但需要 15 声望。给我一个upvote,我也许可以! ;)
    猜你喜欢
    • 2015-03-09
    • 1970-01-01
    • 2014-05-15
    • 2019-07-30
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    相关资源
    最近更新 更多