【问题标题】:Laravel: eager loading both belongsTo and HasMany relationships?Laravel:渴望加载belongsTo和HasMany关系?
【发布时间】:2019-07-26 21:35:59
【问题描述】:

我有两个模型 Product 和 ProductCategory 是相关的,一个产品属于一个产品类别,一个产品类别可以有多个产品。

这是我的模型:

产品:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
    protected $table = 'products';
    public function productcategory()
    {
        return $this->belongsTo('App\Models\ProductCategory');
    }
}

产品类别:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProductCategory extends Model
{
    protected $table = 'productcategories';
    public function products()
    {
        return $this->HasMany('App\Models\Product');
    }
}

我检索所有类别及其各自附加的产品,如下所示:

$productCategories = ProductCategory::with('products')->get();

这可行,但我想要它以便我可以从产品中访问产品类别信息,这是因为我使用 vue 循环遍历每个类别产品,但我需要从产品本身访问类别信息,而不仅仅是 product_category_id但其他领域!

在我的组件中我想这样做:

product.productcategory.name

但目前我只能访问:

product.product_category_id

我不想对我的 API 进行 ajax 调用来获取这些信息,我该如何解决这个问题?

【问题讨论】:

  • 您在哪里以及如何使用组件? vue 组件代码可能有助于直接从现有模型中访问类别名称。

标签: javascript php laravel vue.js


【解决方案1】:

您可以像这样轻松使用nested eager loading

$productCategories = ProductCategory::with('products', 'products.productcategory')-&gt;get();

但是你应该考虑直接在你的 vue 文件中重新使用 ProductCategory 值。

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 2016-08-18
    • 2014-04-19
    • 1970-01-01
    相关资源
    最近更新 更多