You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel5中如何使用Eloquent与Query Builder实现相关需求?

Hey there! Let's dive into Laravel 5's Eloquent and Query Builder—these are super powerful tools, so I'll walk you through some common practical implementations that might align with what you're trying to build.

常用 Eloquent & Query Builder 实现示例

1. 基础数据查询

Query Builder 写法

// 获取所有用户,按创建时间倒序,仅返回name和email字段
$users = DB::table('users')
            ->select('name', 'email')
            ->orderBy('created_at', 'desc')
            ->get();

Eloquent 模型写法(假设你已创建User模型)

$users = User::select('name', 'email')
            ->latest('created_at')
            ->get();

2. 关联数据查询(例:用户关联文章)

先在User模型中定义关联关系:

public function posts()
{
    return $this->hasMany(Post::class);
}

然后查询用户及其最新的3篇文章:

$users = User::with(['posts' => function ($query) {
    $query->latest()->take(3);
}])->get();

3. 复杂多条件过滤

// 获取状态为活跃,且注册时间在2023年后,或者邮箱包含@example.com的用户
$users = User::where('status', 'active')
            ->where(function ($query) {
                $query->where('created_at', '>', '2023-01-01')
                      ->orWhere('email', 'like', '%@example.com%');
            })
            ->get();

4. 聚合统计操作

// 获取活跃用户总数
$activeUserCount = User::where('status', 'active')->count();

// 获取所有用户的平均年龄
$averageAge = User::avg('age');

5. 批量数据操作

批量插入

User::insert([
    ['name' => 'Alice', 'email' => 'alice@example.com'],
    ['name' => 'Bob', 'email' => 'bob@example.com'],
]);

批量更新

// 将所有状态为inactive的用户改为active
User::where('status', 'inactive')
    ->update(['status' => 'active']);

If you have more specific needs—like a particular subquery, pagination setup, or advanced association logic—just share the details and I can help refine the implementation further!

内容的提问来源于stack exchange,提问作者Mingeun Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:00:18