我想创建用户,但是在创建用户之前,我想生成用户并为其分配随机数。对于随机数,我想生成随机的前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']),
]);
将此功能放入您的用户模型:
public function setUseridAttribute($value)
{
$nextID = \DB::table('users')->max('id') +1;
$this->attributes['userid'] = rand(1000,9999)*10 + $nextID;
}
请检查下面的代码。希望它会有所帮助。
$digits = 4;
$ra = rand(pow(10, $digits-1), pow(10, $digits)-1);
$count_total_data = User::count();
$set_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();
按照您的要求,这是我通常要做的事情
请注意,我假设您的表结构如下所示
id | userid | firstname | lastname | email | password
userid
默认为空
这里是代码
$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 ]);
就是全部
谢谢