Laravel 多对多使用WhereHas搜索,中间表和要搜索表的字段重合时

whereHas中的内容是对要查询模型字段的搜索

 Course::whereHas('help',function($query){
            $query->where('id',1);
        })->first();

打印sql

select * from `pte_course` where exists (select * from `pte_help` inner join `pte_course_help` on `pte_help`.`id` = `pte_course_help`.`help_id` where `pte_course`.`id` = `pte_course_help`.`course_id` and `id` = 1)

可以看出是对help表的id进行搜索

当中间表的字段和要搜索的表重合时,会报字段冲突错误(中间表使用id作为主键或者其他冲突字段)使用 .区分

 Course::whereHas('help',function($query){
            $query->where('help.id',1);
        })->first();

 

posted @ 2020-05-25 11:18  阿刘啊  阅读(1136)  评论(0编辑  收藏  举报