如何使mysql在laravel中坚持布尔查询模式


public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('phone_no')->unique();
$table->enum('role', ['admin', 'subadmin', 'user'])->index();
$table->boolean('is_active')->default(false)->index();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->json('meta')->nullable();
$table->rememberToken();
$table->timestamps();
});
} 
return User::query()
->when($request->is_active, fn($query) => $query->where('is_active', $request->is_active))
->when($request->role, fn($query) => $query->where('role', $request->role))
->orderBy('created_at', 'desc')
->get();

如果我将is_active作为请求传递为false,它将按false进行筛选,但如果我按true进行筛选,它仍然显示false筛选,但若我将is-active请求传递为1,它将按照true进行筛选。。。我能做些什么来让它通过真/假或0/1进行过滤。谢谢

您可以将值强制转换为bool:

$query->where('is_active', (bool)$request->is_active)

最新更新