我有两个表是User Table和Attendance表,这是我想要做的: 在用户表上插入用户时,也会更新考勤表(用户表的user_id将作为外键插入考勤表),我的用户表的主键是自动增量,这就是为什么我无法手动将其插入考勤表,我该怎么办? laravel中是否有任何可以轻易做到这一点的作弊?
这是我的寄存器控制器
public function register()
{
$myemployee=Employee::all();
return View::make('registration',compact('myemployee'));
}
public function registerEmp()
{
$input = Input::all();
$command = new Employee;
$command->firstname=$input['firstname'];
$command->lastname=$input['lastname'];
$command->position=$input['position'];
$command->save();
return Redirect::action('EmployeesController@register');
}
这是我的迁移
public function up()
{
Schema::create('employees',function($table)
{
$table->increments('id');
$table->text('firstname');
$table->text('lastname');
$table->text('position');
$table->timestamps();
});
public function up()
{
Schema::create('attendances', function(Blueprint $table)
{
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('employees');
$table->timestamp('intime');
$table->timestamp('offtime');
});
}
Employee.php文件
<?php
class Employee extends Eloquent
{
}
?>
答案 0 :(得分:0)
通过将User :: create()的返回值(静态Illuminate \ Database \ Eloquent \ Model)赋值给变量,然后使用该变量插入user_id,可以获取users表中最后插入的ID你的考勤表。
以下是一个例子:
public function registerEmp() {
$input = Input::all();
// Create an employee.
$employee = Employee::create($input);
// Create an attendance entry as well.
Attendance::create([
'user_id'=>$employee->id,
// other columns...
]);
return Redirect::action('EmployeesController@register');}