laravel - 如何通过另一个具有多对多关系的模型来获取模型的所有孩子?
问题描述
我有一个带有列的多级类别模型id, name, category_id
然后我有一个Product
模型,它有很多SubProduct
模型。
和模型Category
与Product
联结表具有多对多关系。
我对如何获得一个类别的所有子产品感到困惑。
如果我这样做:$category->products[0]->childProducts;
我能够获得所有子产品,但是我想要一种方法来做到这一点而无需索引产品并获得所有类别产品。
我的模型的代码如下:
Category.php(注意我用 hasManyThrough 创建了一个 subProducts 函数,但它的用法可能不正确?)
class Category extends Model
{
// Get the sub categories for the category.
public function categories()
{
return $this->hasMany(Category::class, 'category_id');
}
// Get the parent category that owns the category.
public function parent()
{
return $this->belongsTo(Category::class, 'category_id');
}
// Get the products
public function products()
{
return $this->belongsToMany(Product::class);
}
public function subProducts()
{
return $this->hasManyThrough(SkuProduct::class, Product::class);
}
}
产品.php
class Product extends Model
{
public function childProducts()
{
return $this->hasMany(SubProduct::class, 'product_id');
}
/**
* Get the category that owns the product.
*/
public function category()
{
return $this->belongsTo(Category::class);
}
}
子产品.php
class SubProduct extends Mode
{
public function parentProduct()
{
return $this->belongsTo(Product::class, 'product_id');
}
}
解决方案
你试过这个吗?
class Category extends Model
{
public function subProducts()
{
return $this->hasManyThrough(SubProduct::class, Product::class, 'category_id', 'product_id');
}
}
推荐阅读
- javascript - 无法使用 javascript 获取 ckeditor textarea 的 textarea 值
- python - SQlite3 + Python:如何使用两个特定字符串从表中提取记录?
- javascript - 如何使用 gm 更改添加在图像上的文本的字体粗细
- selenium - 将自定义文本记录到 Cucumber JVM 或范围报告
- performance - 在 gatling 性能测试工具中使用 url 编码的有效负载发布请求
- java - 用不同的时间制作重复的 CountDownTimer
- c# - 如何在锯齿状数组中分配数组?
- android - 需要帮助才能在 Android Studio 上的模拟器上运行 Github android 项目
- python - TensorFlow 1.0 和 StyleGAN - InvalidArgumentError:无法分配设备进行操作
- c++ - Windows 或其他系统动态/共享库如何链接到 VS 到 MinGW 不兼容?