【问题标题】:Angularjs + Laravel: Get properties of Eloquent Relationships in nested ng-repeatAngularjs + Laravel:在嵌套的 ng-repeat 中获取 Eloquent 关系的属性
【发布时间】:2016-04-14 01:06:08
【问题描述】:

我要做的是在嵌套的ng-repeat 中获取最深层次的 Eloquent 关系的属性。

这是关系。

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

有一个模型Order,其中hasMany 模型SubItems。这个SubItems 模型belongsTo 一个模型Product

我有一个Order 数组,我想从每个Order 对象中使用ng-repeat 访问相关的Product

    <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-&gt;product-&gt;name}} //This works fine!

控制器方法是...

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

【问题讨论】:

  • 请附上您的控制器代码。 product 不能加载到您的 subItem 模型上,因此我们需要查看您的控制器以提供帮助
  • 谢谢杰夫。我添加了它。信不信由你,当我使用 Laravel 的 forloop 并且 productsubitem 相关时没有错误。
  • 当您调用$subItem-&gt;product 时,它会自动为您加载。如果您希望它出现在 JSON 表单中,您必须手动加载它

标签: php angularjs laravel laravel-5


【解决方案1】:

在您的代码中,您并没有告诉 Laravel 将项目模型预先加载到您的子项模型中。您需要像这样添加产品预加载:

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

并像访问任何其他 javascript 对象一样访问它subItem.product.name

它在 Laravel foreach 循环中为您工作的原因是,当您请求 Laravel 中的属性(即$subItem-&gt;product)而不是作为方法时,Laravel 会自动将关系 Eloquent 对象实例化到 Model 对象中。

【讨论】:

  • 非常感谢。我想再问一个问题……阅读文档后,我认为在 Laravel 中的模型之间放置一个点 (.) 并不是一种常见的做法。在控制器中指示 Eloquent 关系时这样做是否常见?或者,你是怎么找到的?
猜你喜欢
  • 2019-06-17
  • 2018-12-23
  • 2016-09-13
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
相关资源
最近更新 更多