laravel分表的模型和DB数据连接方式
模型
<?php
//第二个数据库
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon; // 必须引入Carbon,否则报类不存在
class Aijieyunuse extends Model
{
// 可选:指定数据库连接(如果用第二个数据库)
protected $connection = 'aijieyunuse';
// 可选:指定表名(如果表名和模型名复数不一致,比如表名是aijieyunkehu)
protected $table = 'aijieyun202601';
// 可选:关闭时间戳(如果表没有created_at/updated_at字段)
public $timestamps = false;
// 可选:指定主键(如果不是id)
protected $primaryKey = 'id';
// 时间戳:分表有created_at/updated_at则为true,无则改为false
public $timestamps = true;
// 批量赋值:补充你的实际业务字段(非必须,仅作兼容)
protected $fillable = ['id', 'created_at', 'updated_at'];
}
DB操作
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
class TestController extends Controller
{
public function testSecondDb()
{
// 1. 查询第二个数据库的数据(核心:指定connection为mysql2)
$users = DB::connection('mysql2')->table('users')->get();
// 2. 插入数据到第二个数据库
DB::connection('mysql2')->table('products')->insert([
'name' => '测试商品',
'price' => 99.99,
'created_at' => now(),
'updated_at' => now(),
]);
// 3. 更新第二个数据库的数据
DB::connection('mysql2')->table('products')
->where('id', 1)
->update(['price' => 89.99]);
// 4. 删除第二个数据库的数据
DB::connection('mysql2')->table('products')->where('id', 1)->delete();
// 5. 也可以先获取连接实例,再操作(适合多次使用的场景)
$secondDb = DB::connection('mysql2');
$orders = $secondDb->table('orders')->where('status', 1)->get();
return response()->json([
'users' => $users,
'orders' => $orders
]);
}
}
最近访问时间:2026-02-05 15:21:59