Files
cunkebao_v3/Moncter/app/controller/UserController.php
2025-11-07 15:40:33 +08:00

104 lines
2.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\controller;
use support\Request;
use app\model\User;
class UserController
{
public function hello(Request $request)
{
$default_name = 'webman';
// 从get请求里获得name参数如果没有传递name参数则返回$default_name
$name = $request->get('name', $default_name);
// 向浏览器返回字符串
return response('hello ' . $name);
}
public function create(Request $request)
{
// 单条创建
$user = User::create([
'name' => 'webman',
'age' => 3,
'email' => 'webman@example.com',
'tags' => ['php', 'webman', 'mongodb'] // MongoDB 原生数组
]);
// 批量创建
// $users = User::insert([
// ['name' => 'user1', 'age' => 20],
// ['name' => 'user2', 'age' => 22]
// ]);
return json([
'success' => true,
'id' => $user->_id, // 自动转为字符串
'created_at' => $user->created_at->format('Y-m-d H:i:s')
]);
}
// 2. 查询文档(支持所有 Eloquent 查询方法)
public function get(Request $request)
{
// 单条查询
$user = User::where('name', 'webman')->first();
// 或通过 ID 查询
// $user = User::find('66e7d8...'); // _id 字符串
// 多条查询(分页、排序、筛选)
$users = User::where('age', '>=', 1)
->whereIn('tags', ['php']) // 数组字段查询
->orderBy('created_at', 'desc')
->paginate(10); // 自动分页(返回 total、per_page 等字段)
// 聚合查询(统计、分组)
$ageCount = User::where('age', '>=', 18)
->groupBy('age')
->selectRaw('age, count(_id) as total')
->get();
return json([
'user' => $user,
'users' => $users->items(),
'total' => $users->total(),
'age_count' => $ageCount
]);
}
// 3. 更新文档
public function update(Request $request)
{
$user = User::find($request->input('id'));
if (!$user) {
return json(['success' => false, 'msg' => '用户不存在'], 404);
}
// 单个更新
$user->age = 4;
$user->save();
// 批量更新
// User::where('name', 'webman')->update(['age' => 4]);
return json(['success' => true, 'updated_at' => $user->updated_at]);
}
// 4. 删除文档
public function delete(Request $request)
{
$user = User::find($request->input('id'));
if (!$user) {
return json(['success' => false, 'msg' => '用户不存在'], 404);
}
$user->delete();
// 批量删除
// User::where('age', '<', 18)->delete();
return json(['success' => true]);
}
}