如何使用 Laravel eloquent 执行 has many through 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18422743/
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
How to perform a has many through statement using laravel eloquent?
提问by Roseann Solano
Say i have three tables users,users_groups and groups.How can i get the user's groups through the users_groups table?
假设我有三个表users、users_groups 和groups。如何通过users_groups 表获取用户的组?
class User extends Eloquent {
protected $table = 'users';
}
class Groups extends Eloquent {
protected $table = 'groups';
}
class Usergroups extends Eloquent {
protected $table = 'users_groups';
}
回答by Hugo Firth
As per your request, I've put together a simple example for your specific use case:
根据您的要求,我为您的特定用例整理了一个简单的示例:
The Tables:
表格:
Eloquent suggests creating 3 database tables in such a scenario: users
, groups
and group_user
.
Eloquent 建议在这种情况下创建 3 个数据库表:users
,groups
和group_user
.
The Laravel documentationstates that:
Laravel文档指出:
The
group_user
table's name is derived from the aplhabetical order of the related model names.
该
group_user
表的名称源自相关模型名称的字母顺序。
The group_user
table should contain the columns user_id
and group_id
which will contain the primary keys of group and user entries. The group_user
table is what's known as a pivot table.
该group_user
表应包含列user_id
,group_id
其中将包含组和用户条目的主键。该group_user
表就是所谓的数据透视表。
This conforms to 3NF(if you're interested).
这符合3NF(如果您有兴趣)。
The Models:
模型:
The User
model should contain the following code:
该User
模型应包含以下代码:
<?php
class User extends Eloquent {
//...Other code…
public function groups()
{
return $this->belongsToMany('Group');
}
}
The Group
model should contain the following code:
该Group
模型应包含以下代码:
<?php
class Group extends Eloquent {
//...Other code…
public function users()
{
return $this->belongsToMany('User');
}
//...Other code…
}
You do notneed a UserGroup
model as found in your question.
你不是需要UserGroup
在你的问题中发现的模型。
Usage:
用法:
In order to retrieve all groups to which a particular user belongs you would do the following:
为了检索特定用户所属的所有组,您将执行以下操作:
$user = User::find($user_id);
$user_groups = $user->groups();
Similarly in order to retrieve all users belonging to a particular group you would do the following:
同样,为了检索属于特定组的所有用户,您将执行以下操作:
$group = Group::find($group_id);
$group_users = $group->users();
In order to add/remove a user to a group would would do the following:
为了将用户添加/删除到组将执行以下操作:
$user = User::find($user_id);
//Add a user
$user->groups()->attach($group_id);
//Detach a user
$user->groups()->detach($group_id);
Other:
其他:
You should read more in the Laravel docs about pivot tables hereand about defining foreign keys (for your pivot table) in your migrations here.
您应该在 Laravel 文档中阅读更多关于此处的数据透视表以及关于在此处的迁移中定义外键(用于您的数据透视表)的内容。
I hope that helps!
我希望这有帮助!