如何在用户注册时在PHP中自动分配用户ID



我正在考虑在用户注册时自动创建用户ID。我使用Laravel对文件进行了编码,数据库使用MySQL。格式应为S0001、S0002、S0003,依此类推。

我应该在MySQL中将其更改为什么类型的数据类型?目前设置为BIGINT。

如果是,那么我该如何处理代码?

下面的代码来自viewuser.blade.hp:

{{View:: make('title')}}
{{View:: make('menu')}}
<div class="table-responsive">
<table class="table table-striped table-sm">
<!-- <caption>List of Users</caption> -->
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">User ID</th>
<th scope="col">Full Name</th>
<th scope="col">Email Address</th>
<th scope="col">Password</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{ $loop->iteration}}</td>
<td>{{ $loop->iteration}}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->password }}</td>
<td>{{ date('D, d F Y', strtotime($user->created_at)) }}</td>
<td>
<a href="/editmyuser?rid={{ $user->id }}">Edit</a>
<a href="/editmyuser?rid={{ $user->id }}">Delete</a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<div class="pagination">
{{ $users->links() }}
</div>

这是注册页面代码,以防有用:

{{View:: make('title')}}
<div>
<form action="register" method="post">
@csrf
<div>
<label for="exampleInputEmail1">Full Name</label>
<input type="text" name="fullname" id="exampleInputName1">
</div>
<div>
<label for="exampleInputEmail1">Email Address</label>
<input type="email" name="email" id="exampleInputEmail1" aria-describedby="emailHelp">
<div id="emailHelp">We'll never share your email with anyone else
</div>
</div>
<div>
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" id="exampleInputPassword1">
</div>
<button type="submit">Register</button>
<button type="button" onclick="javascript:history.back()">Cancel</button>
</form>
</div>
{{View:: make('footer')}}

为什么不在Users表上使用现有的id列,然后在Users表中定义一个prefix列,您可以随时在id之前显示它。

用户表迁移

$table->string('prefix')->default('S');

用户模型

然后,您可以在模型上定义accessor,以返回idprefix列的组合值:

class User extends Model
{
protected function matriculationNumber()
{
return $this->prefix . str_pad($this->id, 3, '0', STR_PAD_LEFT);
}
}

相关内容

  • 没有找到相关文章