laravel-admin 一对一详解

一对一关联

表 demo_users

id username password email
1 tom 123456 tom123@qq.com

定义关联

class User extends Model
{
    protected $table = 'demo_users';

    /*
    *    若但愿在User界面访问到Profile的内容,则必须定义下面的关系
    *    即:User hasOne Profile 【一个User 能够有一个 Profile】
    *   (Profile::class,'user_id','id')
    *   (关联模型,从表外键,主表主键)
    *   注意:不管是主模型仍是从模型,其主外键定义都是同样的
    */
    public function profile(){
        return $this->hasOne(Profile::class,'user_id','id');
    }
}

控制器中访问关联表数据

// 在 User 控制器中展现 Profie 的数据
// Grid
    $grid->column('profile.nick_name',__('NickName'));
    $grid->column('profile.avatar_url',__('Avatar'));
// Show
    $show = new Show(User::with('profile')->findOrFail($id));
    ...
    $show->field('anyName',__('Nick Name'))->as(function (){
        return $this->getRelation('profile')->nick_name;
    });
    $show->field('someName',__('Avatar'))->as(function (){
        return $this->getRelation('profile')->avatar_url;
    });
    ...

表 demo_profiles

id user_id nick_name avatar_url
1 1 tom cat http://.......

定义关联

class Profile extends Model
{
    protected $table = 'demo_profiles';
    /*
    *    若但愿在 Profile 界面访问到 User 的内容,则必须定义下面的关系
    *    即:Profile belongsTo User 【一个Profle 属于 一个User】
    *   (User::class,'user_id','id')
    *   (关联模型,从表外键,主表主键)
    *   注意:不管是主模型仍是从模型,其主外键定义都是同样的
    */
    public function user(){
        return $this->belongsTo(User::class,'user_id','id');
    }
}

控制器中访问关联表数据

// 在 Profie 控制器中展现 User 的数据
// Grid
    $grid->column('user.username', __('User Name'));
    $grid->column('user.email', __('Email'));
// Show
    $show = new Show(User::with('profile')->findOrFail($id));
    ...
    $show->field('anyName', __('User name'))->as(function (){
        return $this->getRelation('user')->username;
    });
    $show->field('someName', __('Email'))->as(function (){
        return $this->getRelation('user')->email;
    });
    ...
相关文章
相关标签/搜索