V
V
vism2017-04-22 04:03:12
Laravel
vism, 2017-04-22 04:03:12

How to rewrite this query in eloquent?

Is it possible to rewrite it normally in eloquent?

$backerQuery = $backerConn
            ->table('LB_backers as lb_ba')
            ->select(\DB::raw('lb_ba.*, 
(SELECT SUM(lb_or.pledge_amt) FROM LB_orders as lb_or WHERE lb_or.backer_id=lb_ba.backer_id ) AS total_spent,
(SELECT COUNT(lb_or.project_id) FROM LB_orders as lb_or WHERE lb_or.backer_id=lb_ba.backer_id ) AS total_projects'))
            ->leftJoin('LB_orders as lb_or', 'lb_ba.backer_id', '=', 'lb_or.backer_id')
            ->leftJoin('LB_projects as lb_pr', 'lb_or.project_id', '=', 'lb_pr.project_id')
            ->leftJoin('LB_categories as lb_ca', 'lb_pr.p_category_id1', '=', 'lb_ca.category_id')
            ->groupBy('lb_ba.backer_id', 'total_projects', 'total_spent');
        if ($atLeast > 0) {
            $backerQuery->having('total_projects', '>', $atLeast);
        }
        if ($amount > 0) {
            $backerQuery->having('total_spent', '>', $amount);
        }
        if (!empty($categories)) {
            $backerQuery->whereIn('lb_pr.p_category_id1', $categories);
        }
        if (!empty($source)) {
            $backerQuery->where('lb_or.source', '=', $source);
        }
        $backersChosen = $backerQuery->get();

If you rewrite it on eloquent, in fact, it will remain so, or can you somehow rewrite the request through relations, in a more beautiful form?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Muhammad, 2017-04-22
@muhammad_97

Use models + methods with relationships: https://laravel.com/docs/5.4/eloquent-relationships

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question