如何在Laravel中使用子查询并将SQL查询转换为laravel

时间:2018-10-28 14:15:20

标签: php sql laravel laravel-query-builder

实际上,我正在做一些维护项目,在此项目中,以前的开发人员使用了核心sql查询,但我想转换为larvel查询。.这是Sql查询:-

$directories = DB::select('
        SELECT d.id, d.name, d.url_match, d.login_url, d.register_url, d.notes, d.logo, d.require_verification FROM `directories` d 
        WHERE d.id
        NOT IN (
            SELECT c.directory_id FROM citations c
            INNER JOIN directories d
            WHERE c.directory_id = d.id
            AND d.allow_citation = 1
            AND c.site_id = ' . $siteID .'
        )
        AND d.allow_citation = 1
        AND d.deleted_at IS NULL
        AND d.tier = '. $tier .'
        ORDER BY d.tier ASC         
    ');

我曾尝试在下面的laravel中进行转换:-

 $directories = Directories::select('id','name','url_match','login_url','register_url','notes',
                 'logo','require_verification')
                ->where(['allow_citation'=>1,'tier'=>$tier])
                ->whereNUll('deleted_at')->get();

有人可以帮助我吗?预先感谢

1 个答案:

答案 0 :(得分:1)

最后我完成了搜索工作:-

$directories = Directories::select('id','name','url_match','login_url','register_url','notes','logo','require_verification')->whereNotIn('id', function($query) use($siteID){
        $query->select('citations.directory_id')
            ->from('citations')
            ->whereRaw('directories.id=citations.directory_id')
            ->where('directories.allow_citation', 1)
            ->where('citations.site_id', $siteID);
        })->where(['allow_citation'=>1,'tier'=>$tier])->whereNUll('deleted_at')->get();