登录
首页 >  文章 >  php教程

LaravelEloquentORM教程与查询技巧

时间:2025-12-01 09:29:35 135浏览 收藏

最近发现不少小伙伴都对文章很感兴趣,所以今天继续给大家介绍文章相关的知识,本文《Laravel Eloquent ORM使用教程及查询技巧》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

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

LaravelEloquentORM怎么用_LaravelEloquentORM基础操作及高级查询技巧

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', '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();
基本上就这些。Eloquent 功能远不止这些,但掌握上述内容已能应对大多数开发需求。实际项目中建议结合文档深入使用事件、观查器、集合操作等特性。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>