我有这样的查询:
select * from `research_purchases` left join `company_research_articles`
on `research_purchases`.`researchable_id` = `company_research_articles`.`id`
and `research_purchases`.`researchable_type` = 'Modules\Analystsweb\Entities
\CompanyResearchArticle'
它不会过滤“Modules \ Analystsweb \ Entities \ CompanyResearchArticle”部分并给我整个结果。 这是我被卡住的部分。
最初我想运行一个Laravel查询。 查询是这样的:
$sales = DB::table('research_purchases')->select(DB::raw('count(research_purchases.id) as sales_count, research_purchases.created_at'))->leftJoin('company_research_articles', function ($join) {
$join->on('research_purchases.researchable_id', '=', 'company_research_articles.id')
->where('research_purchases.researchable_type', '=', 'Modules\Analystsweb\Entities\CompanyResearchArticle');
})
->where('research_purchases.created_at', '>', Carbon::now()->subMonths(11))
->groupBy(DB::raw("MONTH(research_purchases.created_at)"))
->get();
任何建议都将不胜感激。谢谢。
答案 0 :(得分:1)
如果你想左边加入关于右表条件的所有数据,那么你把它放在加入
select * from `research_purchases` left join `company_research_articles`
on `research_purchases`.`researchable_id` = `company_research_articles`.`id`
where `research_purchases`.`researchable_type` = 'Modules\Analystsweb\Entities
\CompanyResearchArticle'
答案 1 :(得分:0)
我还不能发表评论,但你不是指在你的查询中用WH而不是AND吗?
答案 2 :(得分:0)
请尝试whereColumn。
$sales = DB::table('research_purchases')->select(DB::raw('count(research_purchases.id) as sales_count, research_purchases.created_at'))->leftJoin('company_research_articles', function ($join) {
$join->on('research_purchases.researchable_id', '=', 'company_research_articles.id');
})->whereColumn([
['research_purchases.researchable_type', '=', 'Modules\Analystsweb\Entities\CompanyResearchArticle'],
['research_purchases.created_at', '>', Carbon::now()->subMonths(11)]
])->groupBy(DB::raw("MONTH(research_purchases.created_at)"))
->get();
或两者都在哪一边
$sales = DB::table('research_purchases')->select(DB::raw('count(research_purchases.id) as sales_count, research_purchases.created_at'))->leftJoin('company_research_articles', function ($join) {
$join->on('research_purchases.researchable_id', '=', 'company_research_articles.id')
->where(
'research_purchases.researchable_type', '=', 'Modules\Analystsweb\Entities\CompanyResearchArticle')
->where('research_purchases.created_at', '>', Carbon::now()->subMonths(11))
)
})->groupBy(DB::raw("MONTH(research_purchases.created_at)"))
->get();