【问题标题】:Understanding Model Relationship using laravel使用 laravel 理解模型关系
【发布时间】:2020-11-11 17:27:39
【问题描述】:

我目前正在研究 laravel 中的 eloquent orm 关系,现在我只是在阅读 laravel 的文档如何区分一对一、一对多和多对多。今天我创建产品和产品类别。但是我有一个问题,为什么表中的产品类别列不包含在输出中:我将与大家分享我今天创建的示例模型。

我这里有产品类别模型:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class product_category extends Model
{
    //
    // protected $table = 'product_categories';
    public function getProductsRelation() {
        return $this->hasMany(product::class,'product_categorie_id','id');
    }
}

对于我的产品型号:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class product extends Model
{
    //
    protected $table = 'products';
}

我的输出:

为什么此列未包含在输出中:

【问题讨论】:

  • App\product_category::find(1) 将返回产品类别记录 [id=1]。 App\product_category::find(1)-&gt;getProductsRelation 将仅返回与 category 1 相关的产品。如果您需要单个对象中的两条记录,请使用 with() 方法。 App\product_category::with('getProductsRelation')-&gt;find(1);

标签: php laravel


【解决方案1】:

如果您想在一个查询中同时使用两条记录,请使用 with()。

App\product_category::with('getProductsRelation')->find(1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 2020-04-02
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    相关资源
    最近更新 更多