当然可以。如果你使用 Eloquent,你可以简单地使用正常的关系(也许是最简单的方法)。或者,如果您直接使用 SQL 构建器,您可以像往常一样输入表,但您需要遵守您的外键规则。
只要试一试,你就会看到。但请确保导入您使用的类。
在两个模型之间添加关系很容易,但常见的关系类型(和他的观点)之间存在一些差异:一对多、多对一和多对多。
一对多和多对一
假设您的每个项目都有一个创建者,可以说是一个所有者,您可以在 User 和 Project 之间建立 1:n 关系。
public class User {
public function ownedProjects() {
return $this->hasMany('App\Project');
}
}
public class Project {
public function owner() {
return $this->belongsTo('App\User');
}
}
在这种关系中,您可以将Project 附加到User 或告诉Project 他的所有者是谁。
// Attach a project to an user
$project = Project::create([]);
User::find($id)->ownedProjects()->save($project);
// There is also a function saveMany() for an array of projects
// Tell the project who his owner is
$project = Project::create([]);
$project->owner()->associate(User::find($id));
多对多
在您的情况下,我们需要 Users 和 Projects 之间的多对多关系。语法有点不同,但结果很直接。首先我们需要两个模型之间的关系:
public class User {
public function projects() {
return $this->belongsToMany('App\Project');
}
}
public class Project {
public function users() {
return $this->belongsToMany('App\User');
}
}
然后我们可以这样查询关系:
$project = Project::create([]);
User::find($id)->projects()->attach($project->id);
您还可以附加一大堆项目,从另一边做同样的事情,分离模型或同步它们,如果您想确保一个确切的数量(并且只有这个数量)是相关的:
// Adds a relation for the user to projects with ids 1, 2, 4 and 6
User::find($id)->projects()->attach([1, 2, 4, 6]);
// Adds the users with ids 19 and 173 to this project
Project::find($id)->users()->attach([19, 173]);
// Removes the user 19 from the projects relations
Project::find($id)->users()->detach(19);
// Removes all relations between this user and projects that are
// not listed in the synchronization array and adds a relation
// to all projects where none exists yet
User::find($id)->projects()->sync([4, 7, 19, 6, 38]);
这是多对多关系的常规语法,但您也可以像在一对多关系中一样附加模型:
// Creation of project could also be done before and saved to a variable
User::find($id)->projects()->save(Project::create([]));