LoginSignup
0
0

More than 3 years have passed since last update.

Using left join and name column in Model at Laravel Eloquent.

Last updated at Posted at 2019-12-22

Environment

Laravel Framework 6.5.2

Example

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB; // for giving alias to base table

class TableA extends Model
{

    protected $table='table_a';

    public static function getList()
    {
        return DB::table('table_a as a')
            ->leftJoin('table_b as b', 'b.id', '=', 'a.b_id')
            ->get([
                'a.id',
                'b.id as b_id',
                'a.created_at as created_at'
            ]);
    }
}

Note

If each table have created_at and you don't narrow one created_at explicitly, you'll face an error like below

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'created_at' in order clause is ambiguous
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0