how to change sql query to laravel model query without DB

Viewed 48

i am going to change sql query to laravel model query without DB. DB means illuminate\Fascade\DB;

   ->join(array(\DB::expr('(select SUM(p.amount) as paid, p.case_id
                        from payments p
                        where p.status_id = 3
                        group by p.case_id)'),'p'), 'LEFT')->on('p.case_id','=','c.id')

this is sql query of fuelphp. i want to change it with laravel model style. how can i convert?

1 Answers

It is quite difficult guess your whole sql query but in general you need two models. You need create relations between them and then you can use Eloquent.

For example have two models (read tables) - users and payments:

class User extends Model
{
    public function payments(): HasMany
    {
        return $this->hasMany(Payment::class);
    }
}

class Payment extends Model
{
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}

Then you can create Eloquent query:

Payment::with('user')->where('status_id', 3)->sum('amount')
Related