简体   繁体   English

如何将原始 SQL 查询转换为 Laravel 查询生成器

[英]How to convert raw SQL query to Laravel Query Builder

I need a following code to convert to Laravel query can any one help me with these.我需要以下代码来转换为 Laravel 查询,任何人都可以帮助我解决这些问题。

SELECT id, `leave_name`, `total_leave_days`, leave_id, leave_taken_days FROM `leaves` AS t1 INNER JOIN ( SELECT leave_id, SUM(`leave_taken_days`) AS leave_taken_days FROM `leave_applications` WHERE user_id = 2 AND statuses_id = 2 GROUP BY leave_id ) AS t2 ON t1.id = t2.leave_id

I even tried but the output is not showing atall.我什至尝试过,但 output 根本没有显示。

$user_leaves = DB::table('leaves')
        ->select('id', 'leave_name', 'total_leave_days', 'leave_id', 'leave_taken_days')
        ->join('leave_application', 'leave_application.leave_id', '=', 'leave.id')
        ->select('leave_application.leave_id', DB::raw("SUM(leave_taken_days) as leave_application.leave_taken_days"))
        ->where('user_id','=', 2)
        ->where('statuses_id','=', 2)
        ->get();

How can I solve this issue?我该如何解决这个问题?

UPDATE更新

Relations between two models.两个模型之间的关系。

Leave Model留下 Model

public function leave_application()
    {
        return $this->belongsTo(LeaveApplication::class, 'id' , 'leave_id');
    }

Leave Application Model请假申请 Model

 public function leave()
    {
        return $this->belongsTo(Leave::class, 'leave_id', 'id');
    }

Try this:尝试这个:

$user_leaves = Leave::select('leaves.id', 'leaves.leave_name', 'leaves.total_leave_days', 'leave_applications.leave_id',  DB::raw('SUM(leave_applications.leave_taken_days) as leave_taken_days'))
                    ->with('leave_application')
                    ->whereHas('leave_application', function($q) {
                        $q->where('user_id', 2)
                          ->where('statuses_id', 2);
                    })
                    ->groupBy('leaves.id')
                    ->get();

On this topic I would like to give my recommendations for some tools to help you out in the future.关于这个主题,我想就一些工具提出一些建议,以便在将来帮助您。

SQL Statement to Laravel Eloquent to convert SQL to Laravel query builder. SQL 语句到 Laravel Eloquent将 SQL 转换为 Laravel 查询生成器。 This does a decent job at low level queries.这在低级查询上做得不错。 It also saves time when converting old code.它还可以节省转换旧代码的时间。

The other tool I use to view the query that is being run is Clock Work I keep this open in a tab and monitor slow nasty queries or, also gives me perspective on how the query builder is writing SQL. If you have not use this extension I highly recommend getting and using it.我用来查看正在运行的查询的另一个工具是Clock Work我在选项卡中将其保持打开状态并监视缓慢的讨厌查询,或者,还让我了解查询构建器的编写方式 SQL。如果您没有使用此扩展我强烈推荐获取和使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM