Lets say we are using Laravel's query builder:
$users = DB::table('really_long_table_name')
->select('really_long_table_name.id')
->get();
I'm looking for an equivalent to this SQL:
really_long_table_name AS short_name
This would be especially helpful when I have to type a lot of selects and wheres (or typically I include the alias in the column alias of the select as well, and it get's used in the result array). Without any table aliases there is a lot more typing for me and everything becomes a lot less readable. Can't find the answer in the laravel docs, any ideas?
Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add
->withTrashed()
then handle it yourself like->whereRaw('items_alias.deleted_at IS NULL')
Laravel supports aliases on tables and columns with
AS
. TryLet's see it in action with an awesome
tinker
toolTo use in Eloquent. Add on top of your model
protected $table = 'table_name as alias'
..then use in your query like
ModelName::query()->select(alias.id, alias.name)
To use aliases on eloquent models modify your code like this:
This will automatically add table prefix to table names and returns an instance of
Items
model. not a bare query result. AddingDB::raw
prevents laravel from adding table prefixes to aliases.Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.
Hope this helps.