猿问

laravel急切装载领域的变化

我有两个表,“怀旧”和“用户”,它们之间有关系,在我写的用户模型中:


public function nostalgia(){

    return $this->hasMany(Nostalgia::class);

}


public function getPrivatePhone(){

    return substr_replace($this->phone,"***",4,3);

}


在怀旧模式中:


public function user(){

    return $this->belongsTo(User::class);

}

现在,我想在分页模式下获得与用户表有关的所有怀旧信息,以获取用户电话,我想通过我在用户模型中定义的“ getPrivatePhone()”来更改电话号码的某些字符,或者无论如何。我怎样才能做到这一点?我尝试加载此查询,但无法更改电话号码:


Nostalgia::Where("confirm", "=", true)->with('user:id,phone')->Latest()->paginate(6),


慕工程0101907
浏览 122回答 1
1回答

侃侃无极

您可以User按以下方式修改模型:class User extends Model{  protected $appends = ['privatePhone'];  protected $visible = ['id', 'phone', 'privatePhone']  public function getPrivatePhoneAttribute()  {    return substr_replace($this->phone,"***",4,3);  }  //Remove the method getPrivatePhone()  //And keep everything else as it is}$nostalgias = Nostalgia::Where("confirm", true)->with('user')->Latest()->paginate(6);现在,您可以访问一个赞:$nostalgias->first()->user->privatePhone或循环播放:foreach($nostalgias as $nostalgia){  $nostalgia->user->privatePhone;}
随时随地看视频慕课网APP
我要回答