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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM