php - Laravel:仅当关系和关系中的关系存在时才返回结果
问题描述
我有三个模型:ProductType、ProductSubtype 和 ProductSubtypeCategory
产品类型.php
class ProductType extends Model{
// A product type has many subtypes
public function product_subtypes(){
return $this->hasMany(ProductSubtype::class);
}
}
ProductSubtype.php
class ProductSubtype extends Model{
// Each product subtype belongs to a type
public function product_type(){
return $this->belongsTo(ProductType::class);
}
// A product subtype has many categories
public function product_subtype_categories(){
return $this->hasMany(ProductSubtypeCategory::class);
}
}
ProductSubtypeCategory.php
class ProductSubtypeCategory extends Model{
// Each cateogory belongs to a subtype
public function product_subtype(){
return $this->belongsTo(ProductSubtype::class);
}
}
我只想要该子类型中存在产品子类型和子类型类别的产品类型。到目前为止,我已经尝试过了
return ProductType::has('product_subtypes', function ($query){
$query->has('product_subtype_categories');
})->get();
有没有任何官方方法可以从这种嵌套关系中获得我想要的结果?
解决方案
您所做的是正确的,但可以简化。
更改以下内容:
return ProductType::has('product_subtypes', function ($query){
$query->has('product_subtype_categories');
})->get();
至:
return ProductType::has('product_subtypes.product_subtype_categories')->get();
从文档:
访问模型的记录时,您可能希望根据关系的存在来限制结果。例如,假设您想要检索至少有一条评论的所有博客文章。为此,您可以将关系的名称传递给
has
andorHas
方法:
// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();
嵌套
has
语句也可以使用“点”表示法构造。例如,您可以检索至少有一条评论和投票的所有帖子:
// Retrieve posts that have at least one comment with votes...
$posts = App\Post::has('comments.votes')->get();
推荐阅读
- python - 在 Pygame 中获取旋转图像的旋转矩形
- python - 国家仪器长监测Python
- python - 如何从 CoNLL 格式更改为句子列表?
- java - 如何在consumer端设置dubbo序列化?
- reactjs - 在 API Put 中使用 GraphQL 结果
- angular - 图例的重复在 ng2 图表中产生
- javascript - Vue Component数据绑定中如何使用外部函数?
- java - 自定义 DozerConverter 仅在 SpringBoot 测试中调用
- python - 具有不同 y 轴和标题以及相同 x 轴的 3 x 2 子图
- android - 如何设置不同的工具栏并在片段中隐藏上一个工具栏