mysql WhereHas President能更好吗

k5ifujac  于 2023-11-16  发布在  Mysql
关注(0)|答案(1)|浏览(169)

你好,我有一个有数百万条记录的表,我试图通过关系获取模型数据,但是使用where太慢了。
我的代码V1

$influencers = Brand::query()->with('campaignBrandInfluencers.influencer', 'campaignBrandInfluencers.campaign')->whereHas('campaignBrandInfluencers', function ($q) {
            $q->whereIn('status', [CampaignCases::VISIT, CampaignCases::CONFIRMATION, CampaignCases::COVERAGE]);
            $q->whereHas('influencer', function ($q) {
                $q->whereNull('deleted_at');
            });
            $q->whereHas('campaign', function ($q) {
                $q->where('status', 1);
            });
        })->coverageFilter($filter)->orderBy('id', 'desc')->paginate(10);

字符串
我试着用两个步骤来做

return $campaignInfluencers = CampaignInfluencer::query()->whereIn('status', [CampaignCases::VISIT, CampaignCases::CONFIRMATION, CampaignCases::COVERAGE])
            ->whereNotNull('brand_id')->where('brand_id', '>', 0)
            ->with('influencer', 'campaign')
             ->whereHas('influencer', function ($q) {
                $q->whereNull('deleted_at');
            })
            ->whereHas('campaign', function ($q) {
                $q->where('status', 1);
            })
            ->distinct() // Use distinct to select unique brand_id values
            ->pluck('brand_id') // Group by brand_id
            ->toArray();

 $influencers = Brand::query()->with('campaignBrandInfluencers.influencer', 'campaignBrandInfluencers.campaign')->whereIn('id',$campaignInfluencers)->coverageFilter($filter)->orderBy('id', 'desc')->paginate(10);


需要40秒到一分钟,
是的,我在列中添加了一个索引,我通过它搜索
你知道怎么做面糊吗?

kuarbcqp

kuarbcqp1#

你可以使用查询构建器而不是雄辩的SQL。

相关问题