Merhaba,
Öncelikle konuyu anlatabilmem için 3 veritabanı tablo yapımı paylaşacağım.
Kategori:
id
siteID
categoryID
categoryParentID
Ürün:
id
siteID
productID
productCode
barcode
Ürün - Kategori Eşleştirme
id
productID
categoryID
Kategori modelimde şu ilişkileri kullanıyorum:
public function parent(): HasMany
{
return $this->hasMany(IntegrationCategory::class, 'categoryID', 'categoryParentID');
}
public function children(): HasMany
{
return $this->hasMany(IntegrationCategory::class, 'categoryParentID', 'categoryID');
}
public function products(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(IntegrationProduct::class,
IntegrationProductCategoryMatches::class, 'categoryID',
'productID');
}
Aşağıdaki gibi bir eloquent kullanınca seçilen bir kategori ve buna ait alt kategorilere ait ürünleri listeyebiliyorum.
$database_list_product = IntegrationCategory::with(['children' => function ($query) {
$query->with('products');
}])->whereIn('id', $this->categoryIdList)->distinct()->get();
Şu an uğraştığım şey ise barkodu boş olan ürünler hiç ilişkilerde gelmesin.
$database_list_product = IntegrationCategory::with(['children' => function ($query) {
$query->whereHas('products', function ($productQuery) {
$productQuery->whereNotNull("barcode");
});
}])->whereIn('id', [4])->distinct()->get();
Bu şekilde falan getiremedim.
hasMany ile one many yaptık.
belongstoMany ile many many yaptık. Buraya da whereHas ile kontrol getirdim. Nerede hata yapıyorum ?