亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel:僅當關系和關系內的關系存在時,雄辯地返回結果

Laravel:僅當關系和關系內的關系存在時,雄辯地返回結果

PHP
GCT1015 2023-09-15 21:19:00
我有三個模型: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();

來自文檔:

訪問模型的記錄時,您可能希望根據關系的存在來限制結果。例如,假設您想要檢索至少包含一條評論的所有博客文章。為此,您可以將關系的名稱傳遞給hasorHas?方法:

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


查看完整回答
反對 回復 2023-09-15
  • 1 回答
  • 0 關注
  • 110 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號