【发布时间】:2020-04-04 03:46:02
【问题描述】:
我正在 Laravel 中创建这个应用程序。 我有 3 张桌子,员工、部门和薪水 Employees 表有 id、name、dept_name、gender 等列。 部门有 dept_name、emp_id 和 Salaries 有monthlySalaries、emp_id、dept_name
以上所有表格都是由这些各自的模型创建的。
我面临的问题是,当我运行 DatabaseSeeder 时,值确实会输入到数据库中,但它们并不一致,例如。 id = 1 和 Dept_name = Production 的 Employee 表,而在 Department 表中 emp_id = 1 和 Dept_name = 技术支持。 这个问题也流入了薪水表。
我知道,我做错了什么,但我似乎无法弄清楚是什么。 我尝试在 id(employee table) 上创建一个引用 emp_id(salaries) 的 PK,但没有运气。 我什至尝试过更新下面的 DB 播种脚本,但这不会创建薪水条目,在某些情况下甚至将 emp_id(departments) 留空。
任何关于我做错了什么的帮助/指针将不胜感激。 感谢您抽出时间阅读本文:)
员工模型:
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('dept_name');
$table->string('name');
$table->string('gender');
$table->timestamp('date_of_joining');
$table->dateTime('date_of_birth');
$table->timestamps();
}
部门模型:
Schema::create('departments', function (Blueprint $table) {
$table->string('dept_name');
$table->unsignedInteger('employee_id');
$table->timestamps();
});
薪酬模式:
Schema::create('salaries', function (Blueprint $table) {
$table->string('monthlySalary');
$table->unsignedInteger('employee_id');
$table->string('dept_name');
$table->timestamps();
});
数据库播种器
public function run()
{
$this->call([UsersTableSeeder::class]);
//creates employees & Departments
factory(App\Employee::class, 25)->create()->each(function ($employee) {
$department = factory(App\Department::class)->make();
$employee->department()->save($department);
$salary = factory(App\Salary::class)->make();
$employee->salary()->save($salary);
});
}
应用\员工
public function department()
{
return $this->hasOne(Department::class);
}
public function Salary()
{
return $this->hasOne(Salary::class);
}
应用\部门
public function employees()
{
return $this->hasMany(Employee::class);
}
public function salaries()
{
return $this->hasMany(Salary::class);
}
应用\薪资
public function employeeSalary()
{
return $this->belongsTo(Employee::class);
}
【问题讨论】:
-
"员工表id = 1,Dept_name = Production,Department 表emp_id = 1,Dept_name = Tech Support" dept_names 应该相同还是?
-
名称应该相同。本质上,一名员工只能拥有一个部门和一份薪水。这就是我想要在这里实现的目标
-
但是工厂会伪造数据?
-
我同意,faker 会伪造数据,但现在发生的情况是,如果在我的 employees 表中有一行 id 为 1,dept_name 为 Production,departments 表显示 emp_id 为1 但 dept_name 作为技术支持。在这种情况下,它不应该显示生产,即使它是伪造数据。我只是想在不同的表之间建立关系,因为我有几个 SQL 查询,它们运行并显示与 MySQL 终端显示的数据不同的数据