0

Simple question... I can change the name of a table in a query like this:

$users = DB::table('users AS u')->select('name');

Can i do it in some way like this?

$users = App\Models\Users::select('name')->get();
  • 1
    Laravel Query builder automatically assign the alise name to table. Request if you can provide more details what you want to achieve from this or if you are facing some issue. – Deepak May 29 '20 at 13:25

3 Answers3

1

You can do it (source),

App\Models\Users::from( 'users as u' )
    ->select( 'name' )
    ->get();

To get the name directly from the table (source),

$users = new Users;
$table = $users->getTable();
print_r($table);
  • Yes, this will do it. But is there a way to not give the initial name of the table? If my Model i have set protected $table = 'user'; – Kiril Tsvetanov May 29 '20 at 13:52
0

Can you try this:

$users = Users::from('users AS u')
               // Extra Logic
               ->where('u.//field' , '=' , $data)
               ->select('u.name')
               ->get();

Hope It will help You!

void
  • 915
  • 8
  • 20
0

This's called table "Alias" and it's meaningless to set alias in the model, simply because you don't need to define any table name when you're using Laravel ORM.

But in query builder you can set aliases specially when you're trying to join same table multiple times:

 DB::table('table_name AS alias_name');

or in join

$query->join('table_name as alias_name', function ($builder) use ($value) {}
mwafi
  • 3,946
  • 8
  • 56
  • 83