我想创建用户,但在创建之前,我想生成并为其分配随机数。 对于随机数,我想生成前 4 位数字随机和其余其他数字将要分配的主键。 例如:我的数据库中已经有 5 个数据。我想添加一个数据。在数据库中添加数据之前。我想生成 4 位随机数并在数据库中添加 6 的主键。就像数据库中的 3452+6 一样。
$digits = 4;
$ra = rand(pow(10, $digits-1), pow(10, $digits)-1);
return $userid = User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'userid'=> $ra, // here i want to concatenate random number with primary key which is going
to be added
'password' => Hash::make($data['password']),
]);
获取随机数
$digits = 4;
$ra = rand(pow(10, $digits-1), pow(10, $digits)-1);
假设您的数据库中已有 5 个用户。从数据库中获取用户(数据(的总数并增加一个。
$count_total_data = User::count();
$increase_primary_key = $count_total_data + 1;
现在通过连接这两个数字来获取userid
$userid= $ra.$set_primary_key;
现在将用户保存到用户表中
$user = new User;
$user->userid= $userid;
$user->firstname= Input::get('firstname');
$user->lastname= Input::get('lastname');
$user->email= Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
所以总代码给出如下
$digits = 4;
$ra = rand(pow(10, $digits-1), pow(10, $digits)-1);
$count_total_data = User::count();
$increase_primary_key = $count_total_data + 1;
$userid= $ra.$set_primary_key;
$user = new User;
$user->userid= $userid;
$user->firstname= Input::get('firstname');
$user->lastname= Input::get('lastname');
$user->email= Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
将此函数放入您的用户模型中:
public function setUseridAttribute($value)
{
//$nextID = DB::table('users')->max('id') +1;
$this->attributes['userid'] = rand(1000,9999)*10 + $this::max('id') + 1;
}
好的,正如您要求的那样,这就是我通常所做的
请注意,我假设您的表结构如下所示
id | userid | firstname | lastname | email | password
默认情况下,userid
应为空
- 保存后,我从数据库中检索最后插入的ID
- 然后我根据需要自定义新ID
- 然后我将其保存在新字段中(更新表(
这是代码
$userid = User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'userid'=> $ra, // here i want to concatenate random number with primary key which is going
to be added
'password' => Hash::make($data['password']),
]);
现在让我们获取最后插入的id
$id = DB::getPdo()->lastInsertId();
然后让我们随心所欲地制作
$random_id= rand(1000,10000)
$new_id = $id.'_'.$random_id;
现在更新数据库
//Updating row with registration number
User::where('id', $id)->update(['userid' => $new_id ]);
仅此而已
谢谢
rand(( 是 php 中的函数,只需给出最小值和最大值 value.it 将生成一个随机数.并从用户模型中获取一个数字只需执行此操作并保存它
$max_id=User::all()->max('id')+1;
$rand=rand(1000,9999)+$max_id;