Reputation: 301
<?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.
Upvotes: 14
Views: 30515
Reputation: 11
This works for me:
$query = Model::from('table as alias')->get();
And u can check it with:
dd($query->toSql());
Upvotes: 1
Reputation: 53
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();
Upvotes: 1
Reputation: 4320
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.
Upvotes: 21