拉拉维尔 5.2 雄辩的关系渴望获取



>我已经扩展了我的用户模型以具有角色,表格如下

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 IlluminateFoundationAuthUser 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('AppModelsRole', 'id', 'role_id');
    }
}

榜样是

<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Role extends Model {
    protected $table = 'roles';
    public function users()
    {
        return $this->hasMany('AppUser', '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"}

尝试使用完整的 Eloquent 模型 ( User:: ) 而不是裸查询生成器 ( DB::table('users') )。 然后,您将能够使用 with 和其他关系方法(除了所有查询生成器方法):

$users = AppUser::with('role')->skip($skip)->take($size)->get();

最新更新