Laravel-admin show grid 显示关联模型字段

  • usersModel定义如下:
class UsersModel extends Authenticatable implements JWTSubject
{
    use Notifiable;

    public $timestamps = true;

    protected $table = 'users';

    /**
     * @var array
     */
    protected $fillable = [
        'name', 'password',
    ];


    /**
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $with = [
        'profile'
    ];

    /**
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    // 关联用户详情表
    public function profile()
    {
        return $this->hasOne(UserInfoModel::class, 'user_id', 'id');
    }
}
  • userInfoModel定义如下:
class UserInfoModel extends Model
{
    protected $table = 'user_info';

    public $timestamps = false;

    protected $fillable = ['user_id', 'nickname', 'avatar', 'point', 'sex', 'mobile', 'truename', 'birthday', 'email',
        'email_verified', 'email_verified_at', 'register_time'];

    // 关联用户表
    public function user()
    {
        return $this->belongsTo(UsersModel::class, 'user_id', 'id');
    }
}
  • grid方法中显示关联模型字段:
$grid->column('profile.nickname', __('profile.nickname'));
$grid->column('profile.avatar', __('profile.avatar'))->image();

// ....
  • detail方法中显示关联模型字段:
// 这里尝试跟grid中一样通过$show->field('profile.nickname')操作,发现会将profile中所有数据输出为一行。
$show->field('nickname', __('profile.nickname'))->as(function (){
           return $this->profile->nickname;
 });

 $show->field('avatar', __('profile.avatar'))->as(function (){
            return $this->profile->avatar;
        })->image();

// ...
  • 效果如下
 
Laravel-admin show grid 显示关联模型字段_第1张图片
show.png
 
Laravel-admin show grid 显示关联模型字段_第2张图片
detail.png

你可能感兴趣的:(php,Laravel)