Eloquent 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('age', '<>', 10)->get(); // 非10岁用户 $users = User::where('name', 'like', 'd%')->get(); // 名字为d开头的用户 $users = User::where('name', 'like', '%d%')->get(); // 名字含d的用户 // 传递条件数组到 where 函数: $users = User::where([['gender', '=', '1'],['age', '>', '10']])->get(); //10岁以上的男孩 // or语句 $users = User::where('gender', '=', 1)->orWhere('age', '>', '10')->get();
其他where语句
// whereBetween 方法验证列值是否在给定值之间:
$users = User::whereBetween('age', [1, 7])->get(); // 1-7岁的用户
// whereNotBetween 方法验证列值不在给定值之间:
$users = User::whereNotBetween('age', [1, 7])->get(); // 1-7岁以外的用户
// whereIn 方法验证给定列的值是否在给定数组中:
$users = User::whereIn('id', [1, 2, 3])->get();
// whereNotIn 方法验证给定列的值不在给定数组中:
$users = User::whereNotIn('id', [1, 2, 3])->get();
// whereNull 方法验证给定列的值为NULL:
$users = User::whereNull('updated_at')->get();
// whereNotNull 方法验证给定列的值不是 NULL:
$users = User::whereNotNull('updated_at')->get();
// whereDate 方法用于比较字段值和日期:
$users = User::whereDate('created_at', '2018-05-10')->get(); // 20180510注册的用户
// whereMonth 方法用于比较字段值和一年中的指定月份:
$users = User::whereMonth('created_at', '10')->get();
// whereDay 方法用于比较字段值和一月中的制定天:
$users = User::whereDay('created_at', '10')->get();
whereYear 方法用于比较字段值和指定年:
$users = User::whereYear('created_at', '2016')->get();
// whereColumn 方法用于验证两个字段是否相等,也可以传递一个比较运算符到该方法:
$users = User::whereColumn('first_name', 'last_name')->get();
$users = User::whereColumn('updated_at', '>', 'created_at')->get();
// 还可以传递多条件数组到 whereColumn 方法,这些条件通过 and 操作符进行连接:
$users = User::whereColumn([
['first_name', '=', 'last_name'],
['updated_at', '>', 'created_at']
])->get();参数分组
$users = User::where('name', '=', 'xxx')
->orWhere(function ($query) {
$query->where('age', '>', 5)
->where('gender', 1);
})
->get(); // xxx或大于5岁的男孩
where exit
$users = User::whereExists(function ($query) {
$query->select(DB::raw(1))
->from('articles')
->whereRaw('articles.user_id = users.id');
})->get(); // 写过文章的用户
排序
$users = User::orderBy('age', 'desc')->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('name')->having('age', '>', 10)->get(); // 大于10的用户
// 找到所有售价大于 $2,500 的部分, 没理解
$users = User::select('department', DB::raw('SUM(price) as total_sales'))
->groupBy('department')
->havingRaw('SUM(price) > 2500')
->get();
when 条件子句
$sortBy = null; // 当sortBy为null,默认name排序
$users = User::when($sortBy,
function ($query) use ($sortBy) {
return $query->orderBy($sortBy);
}, function ($query) {
return $query->orderBy('name');
})
->get();分页
$users = User::paginate(3); $users->appends(['sort' => 'name'])->links(); // 修改的是连接 $users->withPath('custom/url'); // 约束条件 $users = User::where('id', '>', 2)->paginate(2); $users = User::where('id', '>', 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(['grade' => '2']); // 使用 fill 方法通过数组属性来填充
$user->save();
$row = array('name' => str_random(3),'email' => str_random(3).'@qq.com')
$user = User::create($row); // 返回模型对象
$id = User::insertGetId($row); // 插入记录并返回ID值
$success = User::nsert([
['email' => 'taylor@example.com', 'votes' => 0],
['email' => 'dayle@example.com', 'votes' => 0]
]); // 插入多条更新
单个更新
$user = User::find(1); $user->name = 'new name'; $user->save();
批量更新
User::where('gender', 1)->update(['age' => 1]);
自增自减
$result = User::increment('age'); // 返回修改的行数 $result = User::increment('age', 2); $result = User::decrement('age'); $result = User::decrement('age', 2); $result = User::increment('age',1,['gender' => 1]); // 年龄自增1 且 性别改为1
其他创建方法
$user = User::firstOrCreate(['name' => 'Flight 10']); // 不存在则创建
$user = User::firstOrNew(['name' => 'Flight 10']); // 如果不存在初始化一个新的实$user = User::updateOrCreate(
['name' => 'username', 'age' => '16'],
['grade' => 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('age', 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 = ['deleted_at'];
}
// Laravel Schema 构建器包含一个辅助函数来创建该数据列:
Schema::table('flights', function ($table) {
$table->softDeletes();
});现在,当调用模型的 delete 方法时,deleted_at 列将被设置为当前日期和时间.
当查询一个使用软删除的模型时,被软删除的模型将会自动从查询结果中排除。
软删除的查询
判断给定模型实例是否被软删除,可以使用 trashed 方法:
if ($flight->trashed()) {
//
}
// 如果你想要软删除模型出现在查询结果中,可以使用 withTrashed 方法:
$flights = App\Flight::withTrashed()
->where('account_id', 1)
->get();
// withTrashed 方法也可以用于关联查询中:
$flight->history()->withTrashed()->get();
// onlyTrashed 方法只获取软删除模型:
$flights = App\Flight::onlyTrashed()
->where('airline_id', 1)
->get();
// 恢复软删除模型,使用restore 方法:
$flight->restore();
// 快速恢复多个模型,同样,这也不会触发任何模型事件:
App\Flight::withTrashed()
->where('airline_id', 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!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
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
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
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
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
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
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
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
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.


