以下是一份详细的 Laravel 数据库使用教程,包含基础配置、查询构建器、Eloquent ORM、迁移和填充等核心内容,附带完整示例:
配置 .env
文件
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
支持多种数据库
基本查询
use Illuminate\Support\Facades\DB;
// 获取所有记录
$users = DB::table('users')->get();
// 条件查询
$user = DB::table('users')->where('name', 'John')->first();
// 插入数据
DB::table('users')->insert([
'name' => 'Alice',
'email' => 'alice@example.com',
]);
复杂查询
// 联表查询
$posts = DB::table('posts')
->join('users', 'posts.user_id', '=', 'users.id')
->select('posts.*', 'users.name as author')
->get();
// 聚合函数
$count = DB::table('posts')->count();
事务处理
DB::transaction(function () {
DB::update('update accounts set balance = balance - 100 where id = 1');
DB::update('update accounts set balance = balance + 100 where id = 2');
});
创建模型
php artisan make:model Post -m # -m 同时生成迁移文件
定义模型
// app/Models/Post.php
class Post extends Model
{
protected $fillable = ['title', 'content', 'user_id'];
// 定义与 User 的关系
public function user()
{
return $this->belongsTo(User::class);
}
// 定义与 Comment 的一对多关系
public function comments()
{
return $this->hasMany(Comment::class);
}
}
CRUD 操作
// 创建
$post = Post::create([
'title' => 'Laravel Guide',
'content' => 'Learn Laravel step by step.'
]);
// 查询
$post = Post::find(1);
$posts = Post::where('views', '>', 100)->get();
// 更新
$post->update(['title' => 'Updated Title']);
// 删除
$post->delete();
预加载关联 (Eager Loading)
$posts = Post::with('user', 'comments')->get();
创建 Seeder
php artisan make:seeder PostsTableSeeder
使用模型工厂
// database/factories/PostFactory.php
$factory->define(Post::class, function (Faker $faker) {
return [
'title' => $faker->sentence,
'content' => $faker->paragraph,
'user_id' => User::inRandomOrder()->first()->id,
];
});
// database/seeders/PostsTableSeeder.php
public function run()
{
\App\Models\Post::factory()->count(50)->create();
}
运行填充
php artisan db:seed --class=PostsTableSeeder
分页
$posts = Post::paginate(10); // 每页10条
return view('posts.index', ['posts' => $posts]);
软删除
// 模型中使用 SoftDeletes
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
// 软删除
$post->delete();
// 恢复
Post::withTrashed()->find(1)->restore();
查询日志调试
DB::enableQueryLog();
// 执行查询...
dd(DB::getQueryLog());
$fillable
或 $guarded
属性控制可赋值字段。Laravel 提供了一套完整的数据库操作工具链:
通过组合这些工具,可以高效安全地管理数据库操作。建议结合官方文档(https://laravel.com/docs)深入学习各功能细节。