Skip to content
Advertisement

Laravel Eloquent Join Using Another table

Hi how to convert this SQL query to Laravel Eloquent?
I have three table: payments, devices and users. Payments table does not store user_id. but table has device_id. And device table also has user_id.
I want to get user name which made payment.

select * from payments p 
join devices d on p.device_id = d.devid
join users u on d.user_id = u.id

Advertisement

Answer

it’s very easy

$users = DB::table('payments')
    ->join('devices', 'devices.id', '=', 'payments.device_id')
    ->join('users', 'users.id', '=', 'devices.user_id')
    ->select('payments.*', 'users.name')
    ->get();

Another way is:

We have three models:

  1. User (has many devices)
  2. Device(belongs to user && has many payments)
  3. Payment (belongs to device)

1) User.php

<?php

namespace App;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;

class User extends Authenticatable
{
    use Notifiable;

    public function devices()
    {
        return $this->hasMany(Device::class);
    }

2) Device

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

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

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

3)Payment

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Payment extends Model
{
    //
    public function device()
    {
        return $this->belongsTo(Device::class);
    }
}

and your query should be:

Payament::with(['device','device.user'])->get();
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement