According to Laravel's documentation:Inserts
根据Laravel的文档:插入
Note: When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named "id".
注意:使用PostgreSQL时,insertGetId方法要求将自动递增列命名为“id”。
So, is there a workaround for a custom id
name while using inserGetId
. i.e.
那么,使用inserGetId时是否有自定义ID名称的解决方法。即
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);
1 个解决方案
#1
You can use the Eloquent method Model::create()
to return the object inserted, and obtain the object id, whatever his name is.
您可以使用Eloquent方法Model :: create()返回插入的对象,并获取对象id,无论其名称是什么。
Try this:
$user = User::create(['email'=>'john@ecample.com','votes'=>0]);
$id = $user->custom_id;
This works if your User model is like:
如果您的用户模型如下,则此方法有效:
class User extends Eloquent {
//This custom_id column needs to be of type serial in your table
protected $primaryKey = 'custom_id';
protected $fillable = ['email','votes'];
//...more code ...
}
I hope this works for you
我希望这适合你
#1
You can use the Eloquent method Model::create()
to return the object inserted, and obtain the object id, whatever his name is.
您可以使用Eloquent方法Model :: create()返回插入的对象,并获取对象id,无论其名称是什么。
Try this:
$user = User::create(['email'=>'john@ecample.com','votes'=>0]);
$id = $user->custom_id;
This works if your User model is like:
如果您的用户模型如下,则此方法有效:
class User extends Eloquent {
//This custom_id column needs to be of type serial in your table
protected $primaryKey = 'custom_id';
protected $fillable = ['email','votes'];
//...more code ...
}
I hope this works for you
我希望这适合你