首页 > 解决方案 > 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();

有没有任何官方方法可以从这种嵌套关系中获得我想要的结果?

标签: phplaraveleloquent

解决方案


您所做的是正确的,但可以简化。

更改以下内容:

return ProductType::has('product_subtypes', function ($query){
    $query->has('product_subtype_categories');
})->get();

至:

return ProductType::has('product_subtypes.product_subtype_categories')->get();

文档

访问模型的记录时,您可能希望根据关系的存在来限制结果。例如,假设您想要检索至少有一条评论的所有博客文章。为此,您可以将关系的名称传递给hasandorHas 方法:

// 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();

推荐阅读