使用附加條件透過中間表計算Laravel和Mysql相關的模型的數量。
P粉514458863
P粉514458863 2023-07-24 15:47:02
0
1
453
<p>我有一個MySQL查詢(使用Laravel Eloquent的急切載入和withCount函數建構),在處理大數據集時有一些效能問題,有沒有辦法改進下面的查詢? </p><p>我需要取得所有的商店,並計算與商店相關的產品數量(透過中間表關聯),但是還有一個附加條件,即商店的type_id等於產品的type_id。我認為這個第二個條件導致查詢沒有使用正確的索引。 </p><p>兩個模型之間有一個中間表。 </p><p>商店(id,type_id,owner_id)產品(id,type_id)商店產品(shop_id,product_id)</p><p>我在所有外鍵上都有索引,還在shop_product(shop_id,product_id)上有一個複合索引。 </p><p>所以我的查詢是這樣的:</p><p><br /></p> <pre class="brush:php;toolbar:false;">select shops.*, ( select count (*) from products inner join shop_products on products.id = shop_products.product_id where shops.id = shop_products.shop_id and products.type_id = shops.type_id) from shops where shops.owner_id in (?)</pre> <p>is it possible that this query could be optimized somehow, maybe not using this laravel's withCount whereColumn query?</p> <pre class="brush:php;toolbar:false;">... Shop::withCount(['products' => fn($query) => $query->whereColumn('products. type_id', '=', 'shops.type_id')]);</pre> <p>完整的查詢是這樣的:</p> <pre class="brush:php;toolbar:false;">Shop::whereIn('owner_id', [123]) ->withCount(['products' => fn($query) => $query->whereColumn('products.type_id', '=', 'shops.type_id')]) ->get()</pre> <p>我是否需要在商店(id,type_id)和產品(id,type_id)上新增組合索引? </p>
P粉514458863
P粉514458863

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!