【问题标题】:hasOneThrough Laravel Eloquent RelationshiphasOneThrough Laravel 雄辩的关系
【发布时间】:2020-10-23 20:00:15
【问题描述】:

我有 3 个标签类别、子类别和产品

  • 分类表
---------------------
| id | category_name |
---------------------
  • 子类别表
--------------------------------------------
| id | category_id(FK) | sub_category_name |
--------------------------------------------
  • 产品表
-----------------------------------------------------------------
| id | sub_category_id(FK) | product_name | product_description |
-----------------------------------------------------------------

**如何使用 hasOneThrough 雄辩关系(或使用任何其他关系)获取产品类别名称。 我在产品模型中试过这个**

public function category(){
return $this->hasOneThrough(
    Category::class, 
    SubCategory::class
);

}

但它给出了错误:未知列 'sub_categories.product_id'

【问题讨论】:

  • 类别和子类别可以使用一张表。

标签: laravel eloquent eloquent-relationship


【解决方案1】:

你可以安装这个外部包staudenmeir/belongs-to-through来添加你需要的关系。

class Product extends Model
{
    public function subCategory()
    {
        return $this->belongsTo(SubCategory::class);
    }

    public functoin category()
    {
        return $this->belongsToThrough(Category::class, SubCategory::class);
    }
}

class SubCategory extends Model
{
    public functoin category()
    {
        return $this->belongsTo(Category::class);
    }
}

class Category extends Model
{
    public function subCategories()
    {
        return $this->hasMany(SubCategory::class);
    }

    public functoin products()
    {
        return $this->hasManyThrough(Product::class, SubCategory::class);
    }
}

如果你需要直接从 Product 中访问 Category,并且想使用 laravel 函数,比如$product->category()->attach($category->id) 等,那么你需要这个依赖来实现。

如果你没问题:

    $product->subCategory->category;
    // or
    $product->subCategory->category()->attach($category->id);

那么就不需要依赖了,可以在Product模型上排除category关系。

【讨论】:

  • 那么有没有其他不使用任何外部包的方法?
  • 你错过了一行 - 使用 \Znck\Eloquent\Traits\BelongsToThrough;
  • 并不是一个完整的实现,而是一个解决方案:)。否则我错过了
猜你喜欢
  • 2020-06-03
  • 1970-01-01
  • 2021-10-02
  • 2015-03-14
  • 2018-11-28
  • 2015-01-11
  • 2021-06-03
  • 2020-03-26
相关资源
最近更新 更多