doujishan2247 2018-08-02 05: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 05: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部