我已将我的用户模型扩展为具有角色,表格如下
users(id,name,email,password,remember_token, role_id,created_at,updated_at)
roles(id,name,description,created_at,updated_at)
然后用户模型
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->hasOne('App\Models\Role', 'id', 'role_id');
}
}
并且角色模型是
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model {
protected $table = 'roles';
public function users()
{
return $this->hasMany('App\User', 'role_id', 'id');
}
}
我将用户作为json返回,我希望他们使用查询构建器
来急切地获取角色$users = DB::table('users')->skip($skip)->take($size)->get();
我得到的输出是
{"id":1,"name":"Vinnie Ashken","email":"ashken@eml.cc","password":"$2y$10$fsSxekoktUV5xqe02hMZIuWVRpykmMvjGa.AJUriCEX.KPRfj.Yk.","role_id":1,"remember_token":"184J9pVLf9N2yQ5YfD9Yf5d88uavn0dCFGsAaXnamXKiIbLugIKAVJTmS1t6","created_at":"2016-03-16 00:23:56","updated_at":"2016-03-16 00:42:56"}
我想要的是
{"id":1,"name":"Vinnie Ashken","email":"ashken@eml.cc","password":"$2y$10$fsSxekoktUV5xqe02hMZIuWVRpykmMvjGa.AJUriCEX.KPRfj.Yk.","role":{"id":1, "name":"Administrator","description":"test"},"remember_token":"184J9pVLf9N2yQ5YfD9Yf5d88uavn0dCFGsAaXnamXKiIbLugIKAVJTmS1t6","created_at":"2016-03-16 00:23:56","updated_at":"2016-03-16 00:42:56"}
答案 0 :(得分:0)
尝试使用完整的Eloquent模型(User::
)而不是裸查询构建器(DB::table('users')
)。然后,您将能够使用with
和其他关系方法(除了所有查询构建器方法):
$users = App\User::with('role')->skip($skip)->take($size)->get();