laravel 学习(25)一对一关联模型
发布日期:2021-06-28 19:45:51 浏览次数:2 分类:技术文章

本文共 1079 字,大约阅读时间需要 3 分钟。

实例  user表 和 user_detail

模型User

public function detail(){        return $this->hasOne(UserDetail::class,'user_id');    }

UserDetail模型

class UserDetail extends Model{    protected $table = 'user_detail';    protected $primaryKey = 'id';    protected $guarded = ['id'];}

控制器调用

public function index()    {        $user = User::find(1);        return $user->detail;    }}

结果

{    "id":1,    "user_id":1,    "hobby":"喜欢小姐姐",    "created_at":"2020-06-20T14:58:56.000000Z",    "updated_at":"2020-06-20T14:58:58.000000Z",    "deleted_at":null}

副表调主表

class UserDetail extends Model{    protected $table = 'user_detail';    protected $primaryKey = 'id';    protected $guarded = ['id'];    public function user(){        return $this->belongsTo(User::class,'id');    }}
//一对一 副表调主表$detail = UserDetail::find(1);$detail->user;return $detail->user;

结果

{    "id":1,    "name":"谢谢",    "phone":"15029149794",    "full_name":"谢谢",    "status":1,    "access_token":"wfwefwefwffaf",    "created_at":"2020-06-20T11:11:30.000000Z",    "updated_at":"2020-06-20T11:11:35.000000Z",    "deleted_at":null}

 

转载地址:https://blog.csdn.net/xxpxxpoo8/article/details/106871721 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:laravel 学习(26) 模型 一对多
下一篇:laravel 学习(22)集合的使用

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月26日 15时47分06秒