N+1問題を解決したいです。
商品を買ったバイヤーを判別しているところで、sqlが数回実行されているのでここを解決したいです。
中間テーブルが絡んでいきて少し複雑なので困っています。。。何かアドバイスいただきたいです
Products/list.blade.php
<sold-label :initial-is-buyer-ordered-by='@json((bool)$product->orderBuyer()->count())' > </sold-label>
クエリーの処理
select count(*) as aggregate from `products` 3.32ms /vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:23 project_haiki select * from `products` limit 10 offset 0 270μs /vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:23 project_haiki select * from `users` where `id` = 3 limit 1 330μs /vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php:52 project_haiki select count(*) as aggregate from `buyers` inner join `orders` on `buyers`.`id` = `orders`.`buyer_id` where `orders`.`product_id` = 1 580μs /vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:23 project_haiki select * from `users` where `users`.`id` = 1 limit 1 430μs /Users/okuhataryouhei/Desktop/project/storage/framework/views/22b3889567d438559c96c40c7515953a3454e8c6.php:19 project_haiki select count(*) as aggregate from `buyers` inner join `orders` on `buyers`.`id` = `orders`.`buyer_id` where `orders`.`product_id` = 2 430μs /vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:23 project_haiki select * from `users` where `users`.`id` = 1 limit 1 380μs /Users/okuhataryouhei/Desktop/project/storage/framework/views/22b3889567d438559c96c40c7515953a3454e8c6.php:19 project_haiki select count(*) as aggregate from `buyers` inner join `orders` on `buyers`.`id` = `orders`.`buyer_id` where `orders`.`product_id` = 3 370μs /vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:23 project_haiki select * from `users` where `users`.`id` = 3 limit 1 230μs /Users/okuhataryouhei/Desktop/project/storage/framework/views/22b3889567d438559c96c40c7515953a3454e8c6.php:19 project_haiki select count(*) as aggregate from `buyers` inner join `orders` on `buyers`.`id` = `orders`.`buyer_id` where `orders`.`product_id` = 4 220μs /vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:23 project_haiki select * from `users` where `users`.`id` = 3 limit 1 340μs /Users/okuh
App/Product.php
//---------------------------- //buyerとのリレーション(多対多) //product->orderBuyerで自分を買ったバイヤーの情報取得 //product->orders()->attachで中間テーブル更新 //---------------------------- public function orderBuyer(): BelongsToMany { return $this->belongsToMany('App\Buyer', 'orders','product_id', 'buyer_id')->withTimestamps(); }//第二引数には中間テーブルのテーブル名
App/Buyer.php
public function orderProduct(): BelongsToMany //buyerとのリレーション(多対多)(buyerをもとにproduct取得) { return $this->belongsToMany('App\Product', 'orders','buyer_id', 'product_id')->withTimestamps(); }
テーブル
buyers | products | orders |
---|---|---|
buyer_id | ||
product_id |
あなたの回答
tips
プレビュー