jagadish
jagadish

Reputation: 301

laravel - how to give alias name to eloquent model

<?php

namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
use Sofa\Eloquence\Eloquence;
use Sofa\Eloquence\Mappable;

class User extends Model
{
    use Eloquence, Mappable;

    public $id;
    public $name
}


$data= User::select('distinct User.name')->join('Member as m','User.id','m.userId')->whereRaw('User.name is not null')->get();

I want to avoid Using table name all time instead i want to use alias name.

Upvotes: 14

Views: 30515

Answers (3)

VictorS
VictorS

Reputation: 11

This works for me:

$query = Model::from('table as alias')->get();

And u can check it with:

dd($query->toSql());

Upvotes: 1

Billa
Billa

Reputation: 53

You can add

protected $table = 'users as u';  

-- users is exact your table name in db

And use it like this

User::where('u.id', 1229)->select('u.email')->get();

Upvotes: 1

Sander Visser
Sander Visser

Reputation: 4320

You can use the Model::from method for this

<?php

    class User extends Model
    {
      use Eloquence, Mappable;

      public $id;
      public $name
    }
    $data= User::from('User as u')
             ->select('distinct u.name')
             ->join('Member as m','u.id','m.userId')
             ->whereRaw('u.name is not null')
             ->get();

NOTE: I see a lot upvotes, but this approach isn't good practice. It's better to find a different approach. My advice stay on the common walked paths.

Upvotes: 21

Related Questions