gpt4 book ai didi

php - 我可以使用 php artisan db :seed to seed related tables?

转载 作者:可可西里 更新时间:2023-11-01 07:08:52 24 4
gpt4 key购买 nike

是否可以在 Laravel 5 中使用以下内容为相关表做种?

php artisan db:seed

我有两张 table

users 
id
first name

projects
id
name

和一个数据透视表

project_user
project_id
user_id

我想创建一些用户和一些项目,然后将用户和他们各自的项目关联起来。

播种用户和项目不是问题,但我不确定如何处理数据透视表。

这可能吗?

最佳答案

当然可以。如果您使用的是 Eloquent,则可以简单地处理普通关系(也许是最简单的方法)。或者,如果您直接使用 SQL 构建器,您可以像往常一样提供表格,但您需要遵守您的外键规则。

只要试一试,您就会知道。但请确保导入您使用的类。


在两个模型之间添加关系很容易,但常见关系类型(和他的观点)之间存在一些差异:一对多、多对一和多对多。


一对多和多对一

假设您的每个项目都有一个创建者,也就是所谓的所有者,您可以在 User 之间建立 1:n 关系。和 Project .

public class User {
public function ownedProjects() {
return $this->hasMany('App\Project');
}
}

public class Project {
public function owner() {
return $this->belongsTo('App\User');
}
}

在这种关系中,您可以附加 ProjectUser或告诉 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([]));

关于php - 我可以使用 php artisan db :seed to seed related tables?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31777770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com