Laravel - 访问关系模型与AngularJS [英] Laravel - accessing relationship Models with AngularJS

查看:326
本文介绍了Laravel - 访问关系模型与AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建AngularJS作为我的前端和Laravel作为我的后端单页的应用程序。我碰到试图创造需要访问一个关系到另一个型号表时出现问题。

I am trying to create a single page app with AngularJS as my frontend and Laravel as my backend. I've run into a problem when trying to create a table that needs to access a relationship to another Model.

在这个例子中,假设我有一个显示产品的表。每一件产品也将有一个品牌。

For this example, let's say I have a table that displays products. Every product would also have a brand.

使用Laravel的刀片语法,我会通过解决这个问题:

With Laravel's blade syntax, I would solve this by using:

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

通过角,我希望我能做到这一点:

With Angular, I was hoping I could do this:

<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}}将无法工作,似乎没有要访问父关系的简单方式。

Unfortunately, @{{ product.brand.name }} will not work and there doesn't appear to be an easy way to access parent relationships.

仅供参考,我的控制器是这样的:

FYI, my controller looks like this:

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

The only solution that I can think of is to make a separate api call to the Brand model and store the data into a map object. Then I could call: @{{ brandMap.get(product.brand_id) }}

有谁知道一个简单的解决方案吗?看起来这将是一个常见的​​问题。

Does anyone know of a simpler solution? Seems like it would be a common problem.

感谢。

推荐答案

在获取该产品在Laravel后端不要只用

When fetching the product in your Laravel backend don't just use

Product::find($id);

而是

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

有你去:)通讯文档部分: http://laravel.com/docs /4.2/eloquent#eager-loading

There you go :) Corresponding docs section: http://laravel.com/docs/4.2/eloquent#eager-loading

这篇关于Laravel - 访问关系模型与AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆