Home PHP Framework Laravel Eloquent ORM related operations in Laravel

Eloquent ORM related operations in Laravel

Nov 14, 2019 pm 02:40 PM
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with pivot tables in Laravel Many-to-Many relationships Working with pivot tables in Laravel Many-to-Many relationships Jul 07, 2025 am 01:06 AM

ToworkeffectivelywithpivottablesinLaravel,firstaccesspivotdatausingwithPivot()orwithTimestamps(),thenupdateentrieswithupdateExistingPivot(),managerelationshipsviadetach()andsync(),andusecustompivotmodelswhenneeded.1.UsewithPivot()toincludespecificcol

Adding multilingual support to a Laravel application Adding multilingual support to a Laravel application Jul 03, 2025 am 01:17 AM

The core methods for Laravel applications to implement multilingual support include: setting language files, dynamic language switching, translation URL routing, and managing translation keys in Blade templates. First, organize the strings of each language in the corresponding folders (such as en, es, fr) in the /resources/lang directory, and define the translation content by returning the associative array; 2. Translate the key value through the \_\_() helper function call, and use App::setLocale() to combine session or routing parameters to realize language switching; 3. For translation URLs, paths can be defined for different languages ​​through prefixed routing groups, or route alias in language files dynamically mapped; 4. Keep the translation keys concise and

Sending different types of notifications with Laravel Sending different types of notifications with Laravel Jul 06, 2025 am 12:52 AM

Laravelprovidesacleanandflexiblewaytosendnotificationsviamultiplechannelslikeemail,SMS,in-appalerts,andpushnotifications.Youdefinenotificationchannelsinthevia()methodofanotificationclass,andimplementspecificmethodsliketoMail(),toDatabase(),ortoVonage

Understanding and creating custom Service Providers in Laravel Understanding and creating custom Service Providers in Laravel Jul 03, 2025 am 01:35 AM

ServiceProvider is the core mechanism used in the Laravel framework for registering services and initializing logic. You can create a custom ServiceProvider through the Artisan command; 1. The register method is used to bind services, register singletons, set aliases, etc., and other services that have not yet been loaded cannot be called; 2. The boot method runs after all services are registered and is used to register event listeners, view synthesizers, middleware and other logic that depends on other services; common uses include binding interfaces and implementations, registering Facades, loading configurations, registering command-line instructions and view components; it is recommended to centralize relevant bindings to a ServiceProvider to manage, and pay attention to registration

Configuring and sending email notifications in Laravel Configuring and sending email notifications in Laravel Jul 05, 2025 am 01:26 AM

TosetupemailnotificationsinLaravel,firstconfiguremailsettingsinthe.envfilewithSMTPorservice-specificdetailslikeMAIL\_MAILER,MAIL\_HOST,MAIL\_PORT,MAIL\_USERNAME,MAIL\_PASSWORD,andMAIL\_FROM\_ADDRESS.Next,testtheconfigurationusingMail::raw()tosendasam

Managing database state for testing in Laravel Managing database state for testing in Laravel Jul 13, 2025 am 03:08 AM

Methods to manage database state in Laravel tests include using RefreshDatabase, selective seeding of data, careful use of transactions, and manual cleaning if necessary. 1. Use RefreshDatabasetrait to automatically migrate the database structure to ensure that each test is based on a clean database; 2. Use specific seeds to fill the necessary data and generate dynamic data in combination with the model factory; 3. Use DatabaseTransactionstrait to roll back the test changes, but pay attention to its limitations; 4. Manually truncate the table or reseed the database when it cannot be automatically cleaned. These methods are flexibly selected according to the type of test and environment to ensure the reliability and efficiency of the test.

When to use Contracts versus Facades in Laravel When to use Contracts versus Facades in Laravel Jul 08, 2025 am 12:45 AM

In Laravel, the choice of Contracts and Facades depends on the dependency structure and coupling degree. Contracts are interfaces for easy testing and replacement; Facades provides static syntax sugar, suitable for simple scenarios. 1.Contracts are used to clarify dependencies, improve testability and follow SOLID principles; 2. Facades are suitable for situations where concise syntax is pursued without frequent replacement implementations; 3. Helper functions are more concise but are not conducive to testing and maintenance. Comprehensive use of both is better: use Contracts for complex logic, and use Facades for simple operations.

Strategies for optimizing Laravel application performance Strategies for optimizing Laravel application performance Jul 09, 2025 am 03:00 AM

Laravel performance optimization can improve application efficiency through four core directions. 1. Use the cache mechanism to reduce duplicate queries, store infrequently changing data through Cache::remember() and other methods to reduce database access frequency; 2. Optimize database from the model to query statements, avoid N 1 queries, specifying field queries, adding indexes, paging processing and reading and writing separation, and reduce bottlenecks; 3. Use time-consuming operations such as email sending and file exporting to queue asynchronous processing, use Supervisor to manage workers and set up retry mechanisms; 4. Use middleware and service providers reasonably to avoid complex logic and unnecessary initialization code, and delay loading of services to improve startup efficiency.

See all articles