【问题标题】:change in field of Eager Loading in laravellaravel 中 Eager Loading 字段的变化
【发布时间】:2019-04-23 17:40:08
【问题描述】:

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

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),

【问题讨论】:

    标签: php mysql laravel


    【解决方案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;
    }
    

    【讨论】:

    • 它很棒,但我想将此查询用作 api,并且我不想在查询中获取所有用户数据,我该如何选择“privatePhone”
    • 更新了问题,查看User 具有可见属性的模型。
    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 2021-10-17
    • 1970-01-01
    • 2017-08-19
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    相关资源
    最近更新 更多