hasOneThrough Laravel Eloquent 关系

hasOneThrough Laravel Eloquent Relationship

我有 3 个标签类别,sub_categories 和产品

---------------------
| id | category_name |
---------------------
--------------------------------------------
| id | category_id(FK) | sub_category_name |
--------------------------------------------
-----------------------------------------------------------------
| id | sub_category_id(FK) | product_name | product_description |
-----------------------------------------------------------------

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

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

}

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

你可以安装这个外部包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,并想使用 laravels 函数,如 $product->category()->attach($category->id) 等,那么您需要这个依赖项来实现。

如果你觉得可以:

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

那你就不需要依赖了,你可以排除Product模型上的类目关系。