Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 952
jagadish Avatar asked May 09 '17 09:05

jagadish


2 Answers

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.

like image 176
Sander Visser Avatar answered Sep 25 '22 08:09

Sander Visser


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();
like image 31
Billa Avatar answered Sep 24 '22 08:09

Billa