1 回答
TA贡献1830条经验 获得超9个赞
乍一看,您的表结构的一些问题非常明显。
您似乎正在尝试向表中添加一
user_id
列companies
。假设您的公司有不止一名员工,这不是一个好主意。如果要使用
NOT NULL
列,最好为每个列定义一个默认值。
所以我们可以从编写类似这样的迁移开始,包括公司/用户和部门/用户关系的数据透视表:
// companies
Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('contact_email')->default('');
$table->string('contact_phone')->default('');
$table->timestamps();
});
// departments
Schema::create('departments', function (Blueprint $table) {
$table->id();
$table->foreignId('company_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('contact_email')->default('');
$table->string('contact_phone')->default('');
$table->timestamps();
});
// users
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('name')->default('');
$table->string('phone')->default('');
$table->integer('user_type')->default(0);
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('company_user', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('company_id')->constrained()->onDelete('cascade');
});
Schema::create('department_user', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('department_id')->constrained()->onDelete('cascade');
});
现在我们有了表之间的链接。部门是公司的一部分;一个用户可以是多个部门和/或多个公司的一部分。这导致以下关系:
class User extends Model {
// many-to-many
public function companies() {
return $this->belongsToMany(App\Company::class);
}
// many-to-many
public function departments() {
return $this->belongsToMany(App\Department::class);
}
}
class Company extends Model {
public function departments() {
// one-to-many
return $this->hasMany(App\Department::class);
}
public function users() {
// many-to-many
return $this->belongsToMany(App\User::class);
}
}
class Department extends Model {
public function company() {
// one-to-many (inverse)
return $this->belongsTo(App\Company::class);
}
public function users() {
// many-to-many
return $this->belongsToMany(App\User::class);
}
}
现在这样的代码应该可以工作了:
$user = factory(User::class)->create();
$company = factory(Company::class)->create();
$user->companies()->attach($company);
$company->departments()->create([
'name' => 'Department 1',
'contact_email' => 'department1@example.test',
'contact_phone' => '123456789',
]);
具体来说,该attach方法用于根据您的原始表格布局更新您似乎没有定义的多对多关系。
- 1 回答
- 0 关注
- 73 浏览
添加回答
举报