简体   繁体   English

表之间的Laravel关系

[英]Laravel Relationship Between Tables

I have generate the following database table and need to create model form them. 我已经生成了以下数据库表,并且需要从中创建模型。

Diagram图

Creating a model seems to be an easy task, but I am confused how should i define the relationship between two tables. 创建模型似乎是一件容易的事,但是我很困惑如何定义两个表之间的关系。 In users table RoleId is foreign key. users表中, RoleId是外键。 My question is where and how should I define the relationship (in User model or Role model). 我的问题是我应该在哪里以及如何定义关系(在用户模型或角色模型中)。 Should I use hasOne , hasMany , or belongsTo 我应该使用hasOnehasMany还是belongsTo

In your User model 在您的用户模型中

public function roles()
{
    return $this->hasOne('Role', 'id', 'RoleId');
}

In your Role model 在您的榜样中

public function users()
{
    return $this->belongsTo('User', 'RoleId', 'id);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM