laravel - 如何为eloquent模型提供别名

时间:2017-05-09 09:21:37

标签: laravel eloquent

<?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();

我想避免一直使用表名,而是想使用别名。

3 个答案:

答案 0 :(得分:7)

您可以使用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(); 方法进行此操作

map = []
walls = [(0,3), (0,4), (0,5), (0,7), (2,7), (3,7), (4,7), (5,7), (1,7),
(5,6), (5,4), (2,3), (2,4), (3,5), (3,0), (3,1), (3,2), (7,0), (7,1), (7,5), 
(7,6), (7,7), (8,7)]
for x in range(9):
    for y in range(9):
        for a in range(len(walls)):
            if walls[a][0] == x and walls[a][1] == y:
                map.append(tuple((x,y,"w")))
            else:
                map.append(tuple((x,y,"_")))
            break

---> [(0, 0, '_'), (0, 1, '_'), (0, 2, '_'), (0, 3, 'w'), (0, 4, '_'), (0, 5, '_'), (0, 6, '_'), (0, 7, '_'), (0, 8, '_'), (1, 0, '_'), (1, 1, '_'), (1, 2, '_'), (1, 3, '_'), (1, 4, '_'), (1, 5, '_'), (1, 6, '_'), (1, 7, '_'), (1, 8, '_'), (2, 0, '_'), (2, 1, '_'), (2, 2, '_'), (2, 3, '_'), (2, 4, '_'), (2, 5, '_'), (2, 6, '_'), (2, 7, '_'), (2, 8, '_'), (3, 0, '_'), (3, 1, '_'), (3, 2, '_'), (3, 3, '_'), (3, 4, '_'), (3, 5, '_'), (3, 6, '_'), (3, 7, '_'), (3, 8, '_'), (4, 0, '_'), (4, 1, '_'), (4, 2, '_'), (4, 3, '_'), (4, 4, '_'), (4, 5, '_'), (4, 6, '_'), (4, 7, '_'), (4, 8, '_'), (5, 0, '_'), (5, 1, '_'), (5, 2, '_'), (5, 3, '_'), (5, 4, '_'), (5, 5, '_'), (5, 6, '_'), (5, 7, '_'), (5, 8, '_'), (6, 0, '_'), (6, 1, '_'), (6, 2, '_'), (6, 3, '_'), (6, 4, '_'), (6, 5, '_'), (6, 6, '_'), (6, 7, '_'), (6, 8, '_'), (7, 0, '_'), (7, 1, '_'), (7, 2, '_'), (7, 3, '_'), (7, 4, '_'), (7, 5, '_'), (7, 6, '_'), (7, 7, '_'), (7, 8, '_'), (8, 0, '_'), (8, 1, '_'), (8, 2, '_'), (8, 3, '_'), (8, 4, '_'), (8, 5, '_'), (8, 6, '_'), (8, 7, '_'), (8, 8, '_')]

答案 1 :(得分:0)

您可以添加

protected $table = 'users as u';  

-用户与您在db中的表名完全相同

并像这样使用它

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

答案 2 :(得分:0)

这对我有用:

dd($query->toSql());

您可以使用以下方法进行检查:

{{1}}