11
<?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.

jagadish
  • 161
  • 1
  • 2
  • 8
  • So you don't want to write complete path as in the `use` statement ? – Nauman Zafar May 09 '17 at 10:10
  • I want to avoid using User.id,User.name instead I want to use like u.id, u.name respectively by mentioning `u` as alias to User table @NaumanZafar – jagadish May 09 '17 at 10:34
  • Find the answer to similiar question here http://stackoverflow.com/questions/17713730/how-to-alias-a-table-in-laravel-eloquent-queries-or-using-query-builder – Nauman Zafar May 09 '17 at 12:49

3 Answers3

17

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.

Sander Visser
  • 4,144
  • 1
  • 31
  • 42
  • 1
    `User as u` is a little bit redundant since the Model should know its own table name. Hope laravel could improve this. – user1633272 Apr 29 '20 at 04:43
  • 1
    @Sander Visser, I don't think you comprehend what Eloquent's method `from()` actually does... – Vitalij May 16 '20 at 09:55
1

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();
Billa
  • 53
  • 6
0

This works for me:

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

And u can check it with:

dd($query->toSql());
VictorS
  • 1
  • 2