【问题标题】:Laravel insert data to multiple tablesLaravel 向多个表中插入数据
【发布时间】:2019-11-27 09:57:01
【问题描述】:

您好,我需要将注册表单中的数据插入 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

【问题讨论】:

  • 提供您尝试过的代码
  • 向我们展示您已经拥有的代码。
  • 是的,我做到了。我只需要能够同时向用户和用户发送数据的代码。
  • 请放会员型号

标签: php html mysql laravel


【解决方案1】:

首先你的所有字段都像这样创建 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();

}

【讨论】:

  • 然后呢?如何同时向两个表发送数据?
  • 我认为您应该阅读文档。要保存信息,您需要调用我上面已经提到的 save() 方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
  • 2014-12-08
  • 2021-12-08
  • 1970-01-01
  • 2017-06-07
  • 2016-06-30
相关资源
最近更新 更多