如何在laravel中编写内部查询或嵌套查询

时间:2016-11-18 15:29:14

标签: laravel laravel-5 laravel-5.3

我想在下面的查询中在'select'(内部查询)中写'select'。内部查询将用于计数:  从order_id = 2;

的顺序中选择count('id')

和查询是:

$payment_pending_report = DB::connection('mysql_freesubs')->table('contact as c')
                                        ->select("a.name","c.lname","a.amount as pending amount")             
                                        ->join("member AS m", "c.id", "=", "m.cont_id")
                                        ->join("order AS o", "o.memb_id", "=", "m.id")
                                        ->join("account AS a", "c.id", "=", "a.cont_id")
                                        ->where("a.amount_type", "=","dr")
                                        ->get();

1 个答案:

答案 0 :(得分:-1)

这样的事情:

$payment_pending_report = DB::connection('mysql_freesubs')->table('contact as c')
                                    ->select("a.name","c.lname","a.amount as pending amount", "oc.OrderCount as order_count")             
                                    ->join("member AS m", "c.id", "=", "m.cont_id")
                                    ->join("order AS o", "o.memb_id", "=", "m.id")
                                    ->join("account AS a", "c.id", "=", "a.cont_id")
                                    ->join(DB::raw("(SELECT m.id, COUNT(o.some_unique_id) as OrderCount FROM member as m INNER JOIN order as o ON o.memb_id = m.id GROUP BY m.id) AS oc"), function($join)
                                    {
                                        $join->on('m.id', '=', 'oc.id');
                                    })
                                    ->join("(")
                                    ->where("a.amount_type", "=","dr")
                                    ->get();