Я использую Laravel с MySQL на XAMMP.
В настоящее время я пытаюсь установить простую связь между моей таблицей users
и моей таблицей profiles
.Когда создается новый пользователь, я хочу одновременно создать профиль для этого конкретного пользователя.Ссылка на мой uuid "id" из таблицы пользователей на "user_id" в таблице профилей.Так что я могу сослаться на два в моем приложении.
Для этого я добавил функцию загрузки в свою модель "Пользователь".И я пытаюсь
Теперь, когда я создаю нового пользователя, я получаю следующую ошибку:
SQLSTATE [HY000]: Общая ошибка: 1364 Поле 'id' не имеет значения по умолчаниюзначения (SQL: вставить в значения users
(name
, email
, password
, updated_at
, created_at
) (Джеспер Делеуран Ларсен, jesperdeleuranlarsen@gmail.com, $ 2y $ 10 $ mA4jZINdWhJXfbBihilI0.Lqmn3L5iTm9tAuI5FWBVkIdYxu, 2019-06-02 19:56:11, 2019-06-02 19:56:11))
Если я удаляю функцию загрузки в модели User, она работает нормально и генерируетновый пользователь, но таблица профилей, конечно, пуста.Так что я думаю, что ошибка где-то в модели, но я просто не могу понять, что не так.
Поскольку я новичок, скажите, пожалуйста, все ли настроено неправильно.
Очень признателен!
Модель моего пользователя
<?php
namespace App;
use App\Mail\NewUserWelcomeMail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Mail;
class User extends Authenticatable
{
use Uuids; //UUID
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id', 'name', 'email', 'password',
];
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* 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',
];
protected static function boot()
{
parent::boot();
static::created(function ($user) {
$user->profile()->create();
});
}
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Моя миграция для таблицы пользователей
<?php
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->uuid('id');
$table->primary('id');
$table->string('name');
$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');
}
}
Моя миграция для таблицы профилей
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->uuid('user_id');
$table->string('company')->nullable();
$table->string('phone')->nullable();
$table->timestamps();
//Linking profiles table to users table
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('profiles');
}
}
Моя модель профиля
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
use Uuids; //UUID
//Disable fillable
protected $fillable = [
'id', 'user_id', 'company', 'phone',
];
public function user()
{
return $this->belongsTo(User::class);
}
}
Моя черта для создания userids = uuids.php
<?php
namespace App;
use Webpatser\Uuid\Uuid;
use Illuminate\Database\Eloquent\Model;
trait Uuids
{
/**
* Boot function from laravel.
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = Uuid::generate()->string;
});
}
}