我有三個模型:ProductType、ProductSubtype 和 ProductSubtypeCategory產品類型.phpclass ProductType extends Model{ // A product type has many subtypes public function product_subtypes(){ return $this->hasMany(ProductSubtype::class); }}產品子類型.phpclass 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); }}產品子類型類別.phpclass 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();有沒有任何官方方法可以從這種嵌套關系中獲得我想要的結果?
1 回答

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
您所做的事情是正確的,但可以簡化。
更改以下內容:
return?ProductType::has('product_subtypes',?function?($query){? ???$query->has('product_subtype_categories'); })->get();
到:
return?ProductType::has('product_subtypes.product_subtype_categories')->get();
來自文檔:
訪問模型的記錄時,您可能希望根據關系的存在來限制結果。例如,假設您想要檢索至少包含一條評論的所有博客文章。為此,您可以將關系的名稱傳遞給
has
和orHas
?方法:
//?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();
- 1 回答
- 0 關注
- 110 瀏覽
添加回答
舉報
0/150
提交
取消