doujishan2247 2018-08-02 13:21
浏览 42
已采纳

Laravel雄辩与关系破坏

I need to be able to get a Models Relationship including its soft deleted elements, but only for this 1 instance. I do not want to change the model so that every time I use the relationship it returns all the soft deleted records too.

How can I achieve this?

User Model

class User extends Authenticatable
{
  public function contacts(){
    return $this->hasMany('App\Contacts','user_id','id');
  }
}

Controller

$user = User::findOrFail($id);
//Need to be able to get the trashed contacts too, but only for this instance and in this function
$user->contacts->withTrashed(); //Something like this
return $user;

How can I get the trashed rows only this 1 time inside my controller?

Thanks

  • 写回答

3条回答 默认 最新

  • dongwang6837 2018-08-02 13:30
    关注

    You can use withTrashed method in different ways.

    To associate the call with your relationship you can do as follows:

    public function roles() {
        return $this->hasMany(Role::class)->withTrashed();
    }
    

    To use the same in the fly:

    $user->roles()->withTrashed()->get();
    

    For your special scenario:

    $user->contacts()->withTrashed()->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?