首页 > 解决方案 > hasOneThrough Laravel 雄辩的关系

问题描述

我有 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'

标签: laraveleloquenteloquent-relationship

解决方案


你可以安装这个外部包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 模型上的类别关系。


推荐阅读