簡體   English   中英

Laravel 類別關系回報 null

[英]Laravel categories relationship returns null

我正在嘗試為產品和類別制作關系表。

這是我的產品 Model

protected $table = 'products';

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

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

這是我的類別 model:

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

它返回的類別是 null。我的關系表稱為 categories_products,它有 2 個整數 product_id 和 category_id。

您的 model 中應該有一個belongsTomany關系。

產品 Model

protected $table = 'products';

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

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

類別 model

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM