search
HomePHP FrameworkLaravelEloquent ORM related operations in Laravel

定义

操作

获取(查询)

获取集合,(查询列表)

返回值是 IlluminateDatabaseEloquentCollection 的一个实例

获取所有的数据

use App\User;
$users = User::all();

条件获取列表

$users = User::where('active', 1)
             ->orderBy('name', 'desc')
             ->take(10)
             ->get();

获取数据列值

$result = User::where('gender', '1')->pluck('name');
 // 返回 ['name1','name2 ']
// 该自定义键必须是该表的其它字段列名,否则会报错
$result = User::where('gender', '1')->pluck('email','name');
// 返回 {"name1":"ed9@qq.com","name2":"ed89@qq.com"}

获取单个模型,(查询单条数据)

// 通过主键获取模型
$user = User::find(1);
// 获取匹配查询条件的第一个模型...
$user = User::where('active', 1)->first();
//  返回第一个gender为1的用户的名字
$name = User::where('gender', '1')->value('name');
// 传递主键数组来调用 find 方法,这将会返回匹配记录集合:
$users = App\Flight::find([1, 2, 3]);
如果没有任何查询结果,IlluminateDatabaseEloquentModelNotFoundException 异常将会被抛出:
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();

处理结果集

$result = User::where('gender', '1')->chunk(5, function($users) {
            foreach ($users as $user) {
                $name = $user->name;
                echo $name;
            }
}) // 输出名字
// result 为 boolean  
$result = User::where('gender', '1')->chunk(5, function($users) {
            foreach ($users as $user) {
              $name = $user->name;
              if ($name == "dxx5") {
                 echo $name;
                 return false;
              }
           }
}) // 找出某个名字

聚合方法

// 获取总数
$count = Flight::where('active', 1)->count();
// 获取最大值
$max = Flight::where('active', 1)->max('price');
//平均值
$max = Flight::where('active', 1)->avg('price');

条件查询

select查询

  // 查询名字和email
    $users = User::select('name','email as user_email')->get();
    // 返回 [{"name":"name1","user_email":"1@qq.com"}]
    // 查询构建器实例,添加一个查询列到已存在的 select 子句
    $user = User::select('name');
    $users = $user->addSelect('gender')->get();

        

联合

$first = DB::table('users')
            ->whereNull('first_name');
$users = DB::table('users')
            ->whereNull('last_name')
            ->union($first)
            ->get();

注:unionAll 方法也是有效的,并且和 union 有同样的使用方式

Where子句

$users = User::where('gender', '=', 1)->get(); // 男性用户
$users = User::where('gender', 1)->get(); // 同上
$users = User::where('age', '>=', 10)->get(); // 10岁以上用户
$users = User::where(&#39;age&#39;, &#39;<>&#39;, 10)->get(); // 非10岁用户
$users = User::where(&#39;name&#39;, &#39;like&#39;, &#39;d%&#39;)->get(); // 名字为d开头的用户
$users = User::where(&#39;name&#39;, &#39;like&#39;, &#39;%d%&#39;)->get(); // 名字含d的用户
// 传递条件数组到 where 函数:
$users = User::where([[&#39;gender&#39;, &#39;=&#39;, &#39;1&#39;],[&#39;age&#39;, &#39;>&#39;, &#39;10&#39;]])->get(); //10岁以上的男孩
// or语句
$users = User::where(&#39;gender&#39;, &#39;=&#39;, 1)->orWhere(&#39;age&#39;, &#39;>&#39;, &#39;10&#39;)->get();

其他where语句

// whereBetween 方法验证列值是否在给定值之间:
$users = User::whereBetween(&#39;age&#39;, [1, 7])->get(); // 1-7岁的用户
// whereNotBetween 方法验证列值不在给定值之间:
$users = User::whereNotBetween(&#39;age&#39;, [1, 7])->get(); // 1-7岁以外的用户
// whereIn 方法验证给定列的值是否在给定数组中:
$users = User::whereIn(&#39;id&#39;, [1, 2, 3])->get();
// whereNotIn 方法验证给定列的值不在给定数组中:
$users = User::whereNotIn(&#39;id&#39;, [1, 2, 3])->get();
// whereNull 方法验证给定列的值为NULL:
$users = User::whereNull(&#39;updated_at&#39;)->get();
// whereNotNull 方法验证给定列的值不是 NULL:
$users = User::whereNotNull(&#39;updated_at&#39;)->get();
// whereDate 方法用于比较字段值和日期:
$users = User::whereDate(&#39;created_at&#39;, &#39;2018-05-10&#39;)->get(); // 20180510注册的用户
// whereMonth 方法用于比较字段值和一年中的指定月份:
$users = User::whereMonth(&#39;created_at&#39;, &#39;10&#39;)->get();
// whereDay 方法用于比较字段值和一月中的制定天:
$users = User::whereDay(&#39;created_at&#39;, &#39;10&#39;)->get();
whereYear 方法用于比较字段值和指定年:
$users = User::whereYear(&#39;created_at&#39;, &#39;2016&#39;)->get();
// whereColumn 方法用于验证两个字段是否相等,也可以传递一个比较运算符到该方法:
$users = User::whereColumn(&#39;first_name&#39;, &#39;last_name&#39;)->get();
$users = User::whereColumn(&#39;updated_at&#39;, &#39;>&#39;, &#39;created_at&#39;)->get();
        
// 还可以传递多条件数组到 whereColumn 方法,这些条件通过 and 操作符进行连接:
$users = User::whereColumn([
                [&#39;first_name&#39;, &#39;=&#39;, &#39;last_name&#39;],
                [&#39;updated_at&#39;, &#39;>&#39;, &#39;created_at&#39;]
            ])->get();

参数分组

$users = User::where(&#39;name&#39;, &#39;=&#39;, &#39;xxx&#39;)
        ->orWhere(function ($query) {
           $query->where(&#39;age&#39;, &#39;>&#39;, 5)
                 ->where(&#39;gender&#39;, 1);
        })
        ->get(); // xxx或大于5岁的男孩
where exit
$users = User::whereExists(function ($query) {
                $query->select(DB::raw(1))
                      ->from(&#39;articles&#39;)
                      ->whereRaw(&#39;articles.user_id = users.id&#39;);
})->get(); // 写过文章的用户

            

排序

$users = User::orderBy(&#39;age&#39;, &#39;desc&#39;)->get(); // 年龄倒序
$user = User::latest()->first(); //crate_at  最晚的那个
$user = User::oldest()->first(); //crate_at  最早的那个
$users = User::inRandomOrder()->first(); // 随机用户

限定

$users = User::skip(2)->take(3)->get(); // 跳过前2个取中间3个
$users = User::offset(2)->limit(3)->get(); // 同上

分组

$users = User::groupBy(&#39;name&#39;)->having(&#39;age&#39;, &#39;>&#39;, 10)->get(); // 大于10的用户
// 找到所有售价大于 $2,500 的部分, 没理解
$users = User::select(&#39;department&#39;, DB::raw(&#39;SUM(price) as total_sales&#39;))
    ->groupBy(&#39;department&#39;)
    ->havingRaw(&#39;SUM(price) > 2500&#39;)
    ->get();
when 条件子句
$sortBy = null; // 当sortBy为null,默认name排序
$users = User::when($sortBy, 
            function ($query) use ($sortBy) {
                return $query->orderBy($sortBy);
            }, function ($query) {
                return $query->orderBy(&#39;name&#39;);
            })
            ->get();

分页

$users = User::paginate(3);
$users->appends([&#39;sort&#39; => &#39;name&#39;])->links(); // 修改的是连接
$users->withPath(&#39;custom/url&#39;);
// 约束条件
$users = User::where(&#39;id&#39;, &#39;>&#39;, 2)->paginate(2);
$users = User::where(&#39;id&#39;, &#39;>&#39;, 2)->simplePaginate(2);
return $users->toArray();

返回结果:

当调用 paginate 方法时,你将获取IlluminatePaginationLengthAwarePaginator 实例,

调用方法simplePaginate 时,将会获取 IlluminatePaginationPaginator 实例。(不需要知道结果集中数据项的总数)

{
    "current_page" : 1
    "data": [{"id":1,"name":"name1"},{"id":2,"name":"name2"}]
    "from":1
    "last_page":2
    "next_page_url":"http://localhost:8888/user/page?page=2"
    "path":"http://localhost:8888/user/page"
    "per_page":3
    "prev_page_url":null
    "to":3
    "total":6
}

每个分页器实例都可以通过以下方法提供更多分页信息:

$results->count()
$results->currentPage()
$results->firstItem()
$results->hasMorePages()
$results->lastItem()
$results->lastPage() (使用simplePaginate 时无效)
$results->nextPageUrl()
$results->perPage()
$results->previousPageUrl()
$results->total() (使用simplePaginate 时无效)
$results->url($page)

插入

插入

$user = new User;
$user->name = "username";
$user->fill([&#39;grade&#39; => &#39;2&#39;]); // 使用 fill 方法通过数组属性来填充
$user->save();
$row = array(&#39;name&#39; => str_random(3),&#39;email&#39; => str_random(3).&#39;@qq.com&#39;)
$user = User::create($row); // 返回模型对象
$id = User::insertGetId($row); // 插入记录并返回ID值
$success = User::nsert([
    [&#39;email&#39; => &#39;taylor@example.com&#39;, &#39;votes&#39; => 0],
    [&#39;email&#39; => &#39;dayle@example.com&#39;, &#39;votes&#39; => 0]
]); // 插入多条

更新

单个更新

$user = User::find(1);
$user->name = &#39;new name&#39;;
$user->save();

批量更新

User::where(&#39;gender&#39;, 1)->update([&#39;age&#39; => 1]);

自增自减

$result = User::increment(&#39;age&#39;); // 返回修改的行数
$result = User::increment(&#39;age&#39;, 2);
$result = User::decrement(&#39;age&#39;);
$result = User::decrement(&#39;age&#39;, 2);
$result = User::increment(&#39;age&#39;,1,[&#39;gender&#39; => 1]); // 年龄自增1 且 性别改为1

其他创建方法

$user = User::firstOrCreate([&#39;name&#39; => &#39;Flight 10&#39;]); // 不存在则创建
$user = User::firstOrNew([&#39;name&#39; => &#39;Flight 10&#39;]); // 如果不存在初始化一个新的实$user = User::updateOrCreate(
    [&#39;name&#39; => &#39;username&#39;, &#39;age&#39; => &#39;16&#39;],
    [&#39;grade&#39; => 3]
); // 将 16岁的username 改成3年级,没有则创建

删除

$user = User::find(1);
$user->delete(); // 通过主键查询后,删除模型
User::destroy(1); // 直接通过主键删除
User::destroy([1, 2, 3]);
User::destroy(1, 2, 3);
$deletedRows = User::where(&#39;age&#39;, 0)->delete(); //查询 删除
// 注:通过 Eloquent 批量删除时,deleting 和 deleted 事件不会被触发,因为在进行模型删除时不会获取模型。

软删除

当模型被软删除后,它们并没有真的从数据库删除,而是在模型上设置一个 deleted_at 属性并插入数据库,如果模型有一个非空 deleted_at 值,那么该模型已经被软删除了。

启用模型的软删除功能,可以使用模型上的IlluminateDatabaseEloquentSoftDeletes trait并添加 deleted_at 列到 $dates 属性:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Flight extends Model
{
    use SoftDeletes;
    // 应该被调整为日期的属性,并添加 deleted_at 列到数据表
    protected $dates = [&#39;deleted_at&#39;];
}
// Laravel Schema 构建器包含一个辅助函数来创建该数据列:
Schema::table(&#39;flights&#39;, function ($table) {
    $table->softDeletes();
});

现在,当调用模型的 delete 方法时,deleted_at 列将被设置为当前日期和时间.

当查询一个使用软删除的模型时,被软删除的模型将会自动从查询结果中排除。

软删除的查询

判断给定模型实例是否被软删除,可以使用 trashed 方法:

if ($flight->trashed()) {
    //
}
// 如果你想要软删除模型出现在查询结果中,可以使用 withTrashed 方法:
$flights = App\Flight::withTrashed()
            ->where(&#39;account_id&#39;, 1)
            ->get();
            
// withTrashed 方法也可以用于关联查询中:
$flight->history()->withTrashed()->get();
// onlyTrashed 方法只获取软删除模型:
$flights = App\Flight::onlyTrashed()
            ->where(&#39;airline_id&#39;, 1)
            ->get();
            
// 恢复软删除模型,使用restore 方法:
$flight->restore();
// 快速恢复多个模型,同样,这也不会触发任何模型事件:
App\Flight::withTrashed()
    ->where(&#39;airline_id&#39;, 1)
    ->restore();
    
// 也可以用于关联查询:
$flight->history()->restore();
// 永久删除模型,可以使用 forceDelete 方法:
$flight->forceDelete(); // 强制删除单个模型实例...
$flight->history()->forceDelete(); // 强制删除所有关联模型...

The above is the detailed content of Eloquent ORM related operations in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What is the latest Laravel version?What is the latest Laravel version?May 09, 2025 am 12:09 AM

As of October 2023, Laravel's latest version is 10.x. 1.Laravel10.x supports PHP8.1, improving development efficiency. 2.Jetstream improves support for Livewire and Inertia.js, simplifies front-end development. 3.EloquentORM adds full-text search function to improve data processing performance. 4. Pay attention to dependency package compatibility when using it and apply cache optimization performance.

Laravel Migrations: A Beginner's Guide to Database ManagementLaravel Migrations: A Beginner's Guide to Database ManagementMay 09, 2025 am 12:07 AM

LaravelMigrationsstreamlinedatabasemanagementbyprovidingversioncontrolforyourdatabaseschema.1)Theyallowyoutodefineandsharethestructureofyourdatabase,makingiteasytomanagechangesovertime.2)Migrationscanbecreatedandrunusingsimplecommands,ensuringthateve

Laravel migration: Best coding guideLaravel migration: Best coding guideMay 09, 2025 am 12:03 AM

Laravel's migration system is a powerful tool for developers to design and manage databases. 1) Ensure that the migration file is named clearly and use verbs to describe the operation. 2) Consider data integrity and performance, such as adding unique constraints to fields. 3) Use transaction processing to ensure database consistency. 4) Create an index at the end of the migration to optimize performance. 5) Maintain the atomicity of migration, and each file contains only one logical operation. Through these practices, efficient and maintainable migration code can be written.

Latest Laravel Version: Stay Up-to-Date with the Newest FeaturesLatest Laravel Version: Stay Up-to-Date with the Newest FeaturesMay 09, 2025 am 12:03 AM

Laravel's latest version is 10.x, released in early 2023. This version brings enhanced EloquentORM functionality and a simplified routing system, improving development efficiency and performance, but it needs to be tested carefully during upgrades to prevent problems.

Mastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMay 08, 2025 am 12:25 AM

Laravelsoftdeletesallow"deletion"withoutremovingrecordsfromthedatabase.Toimplement:1)UsetheSoftDeletestraitinyourmodel.2)UsewithTrashed()toincludesoft-deletedrecordsinqueries.3)CreatecustomscopeslikeonlyTrashed()forstreamlinedcode.4)Impleme

Laravel Soft Deletes: Restoring and Permanently Deleting RecordsLaravel Soft Deletes: Restoring and Permanently Deleting RecordsMay 08, 2025 am 12:24 AM

In Laravel, restore the soft deleted records using the restore() method, and permanently delete the forceDelete() method. 1) Use withTrashed()->find()->restore() to restore a single record, and use onlyTrashed()->restore() to restore a single record. 2) Permanently delete a single record using withTrashed()->find()->forceDelete(), and multiple records use onlyTrashed()->forceDelete().

The Current Laravel Release: Download and Upgrade Today!The Current Laravel Release: Download and Upgrade Today!May 08, 2025 am 12:22 AM

You should download and upgrade to the latest Laravel version as it provides enhanced EloquentORM capabilities and new routing features, which can improve application efficiency and security. To upgrade, follow these steps: 1. Back up the current application, 2. Update the composer.json file to the latest version, 3. Run the update command. While some common problems may be encountered, such as discarded functions and package compatibility, these issues can be solved through reference documentation and community support.

Laravel: When should I update to the last version?Laravel: When should I update to the last version?May 08, 2025 am 12:18 AM

YoushouldupdatetothelatestLaravelversionwhenthebenefitsclearlyoutweighthecosts.1)Newfeaturesandimprovementscanenhanceyourapplication.2)Securityupdatesarecrucialifvulnerabilitiesareaddressed.3)Performancegainsmayjustifyanupdateifyourappstruggles.4)Ens

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version