laravel - 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'
解决方案
你可以安装这个外部包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 模型上的类别关系。
推荐阅读
- javascript - 如何创建可随浏览器窗口调整大小而很好缩放的画布
- c# - C#。得到 x 产生由方程 y=a*x^2+b*x+c 给出的抛物线的最小值
- mysql - MySQL找到每月的最大日期
- java - 每个实例是否隔离了 Google App Engine tmp 文件夹?
- c# - 在 c# 中限制外部进程的更好方法
- design-patterns - 我们如何使用 Financial Force FFLIB 使用自定义异常
- javascript - 通用搜索管道Angular6
- python - Python:如何更有效地获取特定时区的当前日期
- video - 让 Google Home 在我的 chromecast 上播放 mp4 视频
- jmeter - 从 Jmeter 中的 csv 读取时在请求中附加反逗号?