Laravel model::create() 不返回主键
Laravel model::create() not returning the primary key
我有以下授权 table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class CreateAuthTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('auth', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('email', 255)->index()->unique();
$table->string('password', 96);
$table->timestamps();
});
DB::statement('ALTER TABLE auth ALTER COLUMN id SET DEFAULT uuid_generate_v4();');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('auth');
}
}
这是模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;
class User extends Authenticable
{
use HasApiTokens;
protected $table = "auth";
protected $fillable = ["email", "password"];
public $incrementing = false;
protected $keyType = 'string';
protected $casts = [
'id' => 'string'
];
private $hashOptions = [
'memory' => 1024,
'time' => 2,
'threads' => 1
];
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value, $this->hashOptions);
}
}
在 UserController
中,我这样创建用户:
<?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
"email" => "required|email|unique:auth",
"password" => "required|string|min:2|max:255",
"password_confirm" => "required|same:password"
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
$credentials = $request->only('email', 'password');
$exists = User::where('email', $credentials['email'])->first();
if ($exists) {
return response()->json([
"error" => "Email already exists"
], 409);
}
$user = User::create($credentials);
dd($user->id); // This is always null
return response()->json([
'data' => [
"id" => $user->id,
"email" => $request->email,
]
]);
}
}
但是,响应 $user->id
始终为空。 Model::create
return 不应该是新建记录的id吗?
我也尝试了一堆这样的组合:
// Models\User.php
public $incrementing = false;
protected $keyType = 'string';
protected $casts = [
'id' => 'string'
];
但结果总是一样的。我正在使用 Laravel 7 和 Postgres SQL 12.3.
只需确保转换为字符串且主键名称正确
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $casts = [
'id' => 'string'
];
protected $primaryKey = "id";
}
如果您将 $incrementing 设置为 false,它会破坏它并始终 return false,因为它告诉代码 id 不是自动生成的,因此永远不会获取。
class User extends Model
{
public $incrementing = false;
// ...
}
$user = new User;
$user->save();
dd($user->id);
// null
还要确保在迁移中启用 uuid 扩展
<?php
class AddUuidExtensionToPostgre extends Migration
{
public function up()
{
DB::statement('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";');
}
public function down()
{
DB::statement('DROP EXTENSION IF EXISTS "uuid-ossp";');
}
}
这里有一个例子
Schema::create('users', function (Blueprint $table) {
$table->uuid('id');
$table->primary('id');
// ...
});
DB::statement('ALTER TABLE users ALTER COLUMN id SET DEFAULT uuid_generate_v4();');
我有以下授权 table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class CreateAuthTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('auth', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('email', 255)->index()->unique();
$table->string('password', 96);
$table->timestamps();
});
DB::statement('ALTER TABLE auth ALTER COLUMN id SET DEFAULT uuid_generate_v4();');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('auth');
}
}
这是模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;
class User extends Authenticable
{
use HasApiTokens;
protected $table = "auth";
protected $fillable = ["email", "password"];
public $incrementing = false;
protected $keyType = 'string';
protected $casts = [
'id' => 'string'
];
private $hashOptions = [
'memory' => 1024,
'time' => 2,
'threads' => 1
];
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value, $this->hashOptions);
}
}
在 UserController
中,我这样创建用户:
<?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
"email" => "required|email|unique:auth",
"password" => "required|string|min:2|max:255",
"password_confirm" => "required|same:password"
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
$credentials = $request->only('email', 'password');
$exists = User::where('email', $credentials['email'])->first();
if ($exists) {
return response()->json([
"error" => "Email already exists"
], 409);
}
$user = User::create($credentials);
dd($user->id); // This is always null
return response()->json([
'data' => [
"id" => $user->id,
"email" => $request->email,
]
]);
}
}
但是,响应 $user->id
始终为空。 Model::create
return 不应该是新建记录的id吗?
我也尝试了一堆这样的组合:
// Models\User.php
public $incrementing = false;
protected $keyType = 'string';
protected $casts = [
'id' => 'string'
];
但结果总是一样的。我正在使用 Laravel 7 和 Postgres SQL 12.3.
只需确保转换为字符串且主键名称正确
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $casts = [
'id' => 'string'
];
protected $primaryKey = "id";
}
如果您将 $incrementing 设置为 false,它会破坏它并始终 return false,因为它告诉代码 id 不是自动生成的,因此永远不会获取。
class User extends Model
{
public $incrementing = false;
// ...
}
$user = new User;
$user->save();
dd($user->id);
// null
还要确保在迁移中启用 uuid 扩展
<?php
class AddUuidExtensionToPostgre extends Migration
{
public function up()
{
DB::statement('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";');
}
public function down()
{
DB::statement('DROP EXTENSION IF EXISTS "uuid-ossp";');
}
}
这里有一个例子
Schema::create('users', function (Blueprint $table) {
$table->uuid('id');
$table->primary('id');
// ...
});
DB::statement('ALTER TABLE users ALTER COLUMN id SET DEFAULT uuid_generate_v4();');