【问题标题】:Laravel categories relationship returns nullLaravel 类别关系返回 null
【发布时间】:2021-01-22 08:14:24
【问题描述】:

我正在尝试为产品和类别制作关系表。

这是我的产品模型

protected $table = 'products';

    protected $fillable = ['sku', 'slug', 'type'];

    public function category()
    {
        return $this->belongsTo('Modules\Product\Entities\Categories', 'categories_products', 'category_id', 'id');
    }

这是我的类别模型:

protected $table = 'categories';
    
    protected $fillable = ['parent_id', 'name'];


    public function parent()
    {
        return $this->hasOne(self);
    }

    public function products()
    {
        return $this->hasMany('Modules\Product\Entities\Products', 'categories_products', 'product_id', 'id');
    }

每次我尝试获取具有以下类别的产品时:

public function getProducts()
    {
        return Products::with('category')->get();
    }

它返回的类别为空。我的关系表称为 categories_products,它有 2 个整数 product_id 和 category_id。

【问题讨论】:

  • 只需将表名 categories_products 重命名为 category_product 单数项

标签: php laravel


【解决方案1】:

您的模型中应该有belongsTomany 关系。

产品型号

protected $table = 'products';

protected $fillable = ['sku', 'slug', 'type'];

public function categories()
{
    return $this->belongsToMany('Modules\Product\Entities\Categories', 'categories_products', 'product_id', 'category_id');
}

类别模型

protected $table = 'categories';

protected $fillable = ['parent_id', 'name'];


public function parent()
{
    return $this->belongsTo('Modules\Product\Entities\Categories','parent_id','id');
}

public function products()
{
    return $this->belongsToMany('Modules\Product\Entities\Product', 'categories_products', 'category_id', 'product_id');
}

【讨论】:

    猜你喜欢
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 2019-01-12
    • 2016-03-31
    相关资源
    最近更新 更多