Laravel 外键关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37944874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel foreign key relation
提问by Jamie
I've got a strange problem.
我有一个奇怪的问题。
I've a users table and a company table. A User belongsTo a company and a company hasMany users.
我有一个用户表和一个公司表。一个用户属于一个公司,一个公司有很多用户。
Both primary keys of the table are id.
表的两个主键都是 id。
In the laravel documentation I read the following:
在 laravel 文档中,我阅读了以下内容:
Additionally, Eloquent assumes that the foreign key should have a value matching the id column of the parent.
此外,Eloquent 假设外键的值应该与父键的 id 列匹配。
I've got this in my CompanyModel:
我有这个CompanyModel:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class);
}
When I try this:
当我尝试这个时:
$users = CompanyModel::find(1)->users;
dd($users);
It's not working. When I add a foreign key in my relation it works!?:
它不工作。当我在我的关系中添加外键时,它起作用了!?:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class, 'id');
}
This is strange right? What on earth am I doing wrong.
这很奇怪吧?我到底做错了什么。
--EDIT--
- 编辑 -
In my userstable I've got a company_idcolumn!
在我的users桌子上,我有一company_id列!
回答by Koko
Firstly, I would suggest you rename your Model from CompanyModelto Companyand from UserModelto User.
首先,我建议您将模型从CompanyModeltoCompany和 from重命名UserModel为User.
Then ensure you have company_idin your userstable. And in your usersmigration file connect the userstable with the companiestable as such:
然后确保你company_id在你的users桌子上。并在您的users迁移文件中将users表与companies表连接,如下所示:
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
Don't forget to refresh your database.
不要忘记刷新您的数据库。
Then in your models, define the relationships as such:
然后在您的模型中,定义关系如下:
// User model
// Laravel will automatically identify and use the `company_id` field in your reference
public function company(){
return $this->belongsTo(Company::class);
}
// Company model
public function users(){
return $this->hasMany(User::class);
}
You can then fetch your records in your controller as such:
然后,您可以在控制器中获取记录,如下所示:
$user = User::find(1);
$user_company = $user->company; // This might not be necessary in your controller, you can do it in your view
dd($users, $user_company);

