Laravel雄辩,其中没有加入

时间:2016-09-21 08:29:38

标签: php laravel eloquent

有没有办法使用Eloquent重写这个伪查询?

select * from a1, b1
where a1.id=b1.a_id
and not exists (select 1 from a1, b1, c1 where a1.id=b1.a_id and b1.id=c1.b_id)

我尝试了以下方法,但无法弄清楚如何在闭包中传递多个表

A1_Model::where('a1.is_active', 1)
->join('b1', 'b1.a_id', '=', 'a1.id')
->whereNotExists(function ($query) {
            $query->select(\DB::raw(1))
                ->from('a1') // how can I pass two tables here? Array doesn't work
                ->whereRaw('');
        })

3 个答案:

答案 0 :(得分:1)

您可以使用两种方法:

A1_Model::where('a1.is_active', 1)
->join('b1', 'b1.a_id', '=', 'a1.id')
->whereNotExists(function ($query) {
            $query->select(\DB::raw(1))
                ->from('a1')
                ->join('b1', 'b1.a_id', '=', 'a1.id')
                ->join('c1', 'c1.b_id', '=', 'b1.id')
                ->whereRaw('');
        });

您还可以使用DB::tableDB::raw来获得相同的结果。

DB::table(DB::raw('a1', 'b1', 'c1')); //same effect as select from a1, b1, c1

答案 1 :(得分:0)

尝试更多http://php.net/manual/en/functions.anonymous.php

A1_Model::where('a1.is_active', 1)
->join('b1', 'b1.a_id', '=', 'a1.id')
 ->whereNotExists(function ($query) use ($a1){
        $query->select(\DB::raw(1))
            ->from($a1)
            ->whereRaw('');
    })

答案 2 :(得分:0)

编辑:Chibueze Opata建议更好的解决方案

我想除了使用select + db :: raw之外别无他法。这是实际查询

IndicatorModel::where('indicators.is_active', 1)
        ->where('f.is_active', 1)
        ->where('f.logframe_type_id', 1)
        ->whereIn('f.level_id', [1,2])
        ->whereNotExists(function ($query) use ($countryId) {
            $query->select(\DB::raw('1 from indicator_mapping m2, indicators i2, logframes f2
                   where m2.src_indicator_id=i2.id and i2.logframe_id=f2.id and i2.is_active=1
                   and m2.mapped_indicator_id=indicators.id and f2.country_id=' . $countryId));
        })
        ->join('logframes as f', 'f.id', '=', 'indicators.logframe_id')
        ->select('f.id')
        ->groupBy('f.id')
        ->orderBy('f.level_id')
        ->get();