php - Laravel 向多个表中插入数据
问题描述
嗨,我需要将注册表单中的数据插入 2 或 3 个表、用户和成员。当您单击注册按钮时,我需要仅将用户 ID 和密码发送到 users.table 并将其余信息发送到 members.table
*编辑我的模型
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'admin', 'predmet',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
我的迁移
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('admin');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
我需要将 id、predmet 和 name 导入成员表的 cote
解决方案
首先,您的所有字段都像这样创建 nullable()
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->nullable();
$table->integer('admin')->nullable();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken()->nullable();
$table->timestamps();
});
然后在控制器中
public function store()
{
$user = new User;
$user->password = bcrypt($request->password);
$user->save();
$member = new Member;
$member->name = $request->name;
$member->username = $request->username;
$member->email= $request->email;
$member->save();
return back();
}
推荐阅读
- c++ - 如何覆盖我的项目中的柯南共享选项?
- visual-studio-code - 是否可以在 Linux 中使用 vscode-car-plugin 创建 .car 文件?
- webpack - 如何解决这个问题:gulp-inject 没有注入 _custom.scss 和 portal_normal.ftl
- bash - 如何将具有多个标志的字符串分配给可在命令中重用的变量?
- javascript - 复选框起作用,但没有动画
- json - 在 Julia 中使用类似 JSON 的结构遍历嵌套字典
- python - 从 Python 类生成 JSON 模式规范
- java - 为什么我的年度闹钟无法正常工作?
- jquery - Bootsrap 模态 iframe 未显示
- python - 如何将 dl.Overlay 与多个输入一起使用?