答案:Laravel的Eloquent ORM通过模型操作数据库,支持CRUD、关联、作用域等功能;需定义模型类并配置表名、主键等,使用all()、where()、create()、update()、delete()等方法实现数据操作。

Laravel 的 Eloquent ORM 是一个功能强大的 ActiveRecord 实现,让你可以用面向对象的方式操作数据库。每个模型对应一张数据表,通过模型可以轻松实现增删改查、关联查询、作用域、访问器等高级功能。下面从基础操作到高级技巧,带你全面掌握 Eloquent ORM 的使用。
在使用 Eloquent 之前,首先要创建模型类。通常放在 app/Models 目录下(需手动创建目录并更新命名空间)。
例如,有一个 users 表,创建对应的模型:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// 可选:指定表名(如果不遵循复数规则)
protected $table = 'users';
// 可选:指定主键字段
protected $primaryKey = 'id';
// 可选:关闭自动维护 created_at 和 updated_at
public $timestamps = false;
// 允许批量赋值的字段
protected $fillable = ['name', 'email', 'password'];
}
注意:Laravel 默认假设模型名为单数,对应复数形式的数据表(如 User → users),若不符合规则需手动指定 $table。
基于上面的 User 模型,进行常见 CRUD 操作。
查询所有记录:User::all();
User::where('name', 'John')->first();
User::where('active', 1)->get();
$user = new User;
$user->name = 'Alice';
$user->email = 'alice@example.com';
$user->save();
// 或使用 create 方法(需 fillable 配置)
User::create([
'name' => 'Bob',
'email' => 'bob@example.com'
]);
$user = User::find(1);
$user->name = 'New Name';
$user->save();
// 批量更新
User::where('active', 0)->update(['active' => 1]);
// 删除单个
$user = User::find(1);
$user->delete();
// 根据条件删除
User::where('created_at', '<', now()->subDays(30))->delete();
Eloquent 提供了丰富的链式调用方法,支持复杂查询场景。
分页查询:User::where('active', 1)->paginate(10);
在视图中可直接使用 {{ $users->links() }} 渲染分页导航。
排序与限制:User::orderBy('name', 'desc')->limit(5)->get();
在模型中定义常用查询封装:
class User extends Model
{
public function scopeActive($query)
{
return $query->where('active', 1);
}
public function scopeByRole($query, $role)
{
return $query->where('role', $role);
}
}
使用方式:
User::active()->byRole('admin')->get();
用于格式化字段读取或写入时的行为。
// 访问器:获取 name 字段时首字母大写
public function getNameAttribute($value)
{
return ucfirst($value);
}
// 修改器:保存 email 前转为小写
public function setEmailAttribute($value)
{
$this->attributes['email'] = strtolower($value);
}
Eloquent 支持多种关联关系,比如一对一、一对多、多对多等。
用户与文章(一对多):
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
使用:
$user = User::with('posts')->find(1); // 预加载避免 N+1
foreach ($user->posts as $post) {
echo $post->title;
}
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
中间表默认为 role_user,可通过参数自定义。
添加角色:
$user->roles()->attach($roleId);
读取带条件的角色:
$user->roles()->where('active', 1)->get();
以上就是LaravelEloquentORM怎么用_LaravelEloquentORM基础操作及高级查询技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号