学习指东:使用模型创建 uuid 主键数据的两种方式

Laravel框架
428
0
0
2022-05-07
使用场景:使用模型创建一条数据,且 id 使用 uuid 自动接管;
必备知识:没学过 PHP,没啥必备的;

这里不说建表、创建模型了,直奔主题!

模型(Tabs)

use Ramsey\Uuid\Uuid; //方式1
// use Illuminate\Support\Str; //方式2
class Tabs extends Model
{
/**
* 关闭主键的自动增长(id)
* @var string
*/
public $incrementing = false;
/**
* 配置允许操作的字段(自动接管id,这里无需配置)
* @var array
*/
protected $fillable = ['title'];
/**
* 模型的 "booted" 方法(使用模型create时自动接管id)
* @return void
*/
protected static function booted()
{
static::creating(function ($tabs) {
if (! $tabs->getKey()) {
$tabs->{$tabs->getKeyName()} = (string) Uuid::uuid4()->getHex(); //方式1:uuid插件
//$tabs->{$tabs->getKeyName()} = (string) Str::uuid();; //方式2:Str方法
}
});
}
}

控制器(TabsController)

class TabsController extends Controller
{
/**
* Store a newly created resource in storage.
* 演示代码
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = $request->only([ 'title']);
$res = Tabs::create($data);
return response($res);
}
}

响应(方式1)

{
"title": "测试标签1",
"id": "q8fdf2d0c38d8sfdbjfc2s743dfba2af"
}

使用的插件

其他选择

webpatser/laravel-uuid

就这样,打完收工!如有补充,请在下方评论区讨论。