2017-05-16 56 views
0

我有3個模型:手機,產品和商店。addGlobalScope與計數關係的關係

手機有許多屬於商店的產品。

我想添加一個全球範圍,以便每次加載電話時,產品和商店的計數都會自動加載。

products_count正常工作,但stores_count有點棘手,因爲商店不是電話的關係,而是產品的關係。

我試過以下,但它給我一個錯誤「方法getRelated不存在。」,我假設,因爲stores()現在返回一個集合。

有關如何添加stores_count的任何想法?

public static function boot(){ 

    parent::boot(); 

    static::addGlobalScope('products', function ($builder){ 

     $builder->withCount('products'); 
     $builder->withCount('stores'); <----- gives error 
    }); 
} 

public function products(){ 

    return $this->hasMany(Product::class); 
} 

public function stores(){ 
    $store_ids = $this->products()->get(['store_id'])->unique(); 

    return Store::find($store_ids); 
} 

@Sandeesh回答後更新。

我試圖使用hasManyThrough,但它返回一個空的集合,這是錯誤的。 當我dd($ phone-> products);我可以看到有7個產品有3個不同的商店。

public function stores(){ 

    return $this->hasManyThrough(Store::class, Product::class, 
     'store_id', 'id'); 
} 

數據庫模式

Phone 
-id 

Product 
-id 
-phone_id 
-product_id 
-store_id 

Store 
-id 

更新2

所以我設法從上面的商店(所產生的查詢)方法。

select `phones`.*, 
(select count(*) from `products` where `phones`.`id` = `products`.`phone_id`) as `products_count`, 
(select count(*) from `stores` inner join `products` on `products`.`id` = `stores`.`id` where `phones`.`id` = `products`.`store_id`) as `stores_count` 
from `phones` where `slug` = ? limit 1 

問題出現在第三行。查詢是搞砸了,不知道關係有什麼問題。

回答

0

可以使用hasManyThrough

https://laravel.com/docs/5.4/eloquent-relationships#has-many-through

public function stores() 
{ 
    return $this->hasManyThrough(Store::class, Product::class); 
} 

編輯

這應該給你你需要什麼。但渴望加載總是更好

protected $appends = [ 
    'productCount', 
    'storeCount' 
]; 

public function getProductCountAttribute() 
{ 
    return $this->products()->count(); 
} 

public function getStoreCountAttribute() 
{ 
    return Store::whereIn('id', $this->products()->pluck('store_id')->toArray())->count(); 
} 
+0

謝謝,沒有工作,因爲它,我更新了我的問題。 – George

+0

你可以添加商店結構嗎?好像你錯過了它 – Sandeesh

+0

Ooops。添加。它只有一個ID .. – George