Eloquent ORM seems like a simple mechanism, but under the hood, there are many semi-hidden functions and little-known ways to achieve more functionality. In this article, I'll demonstrate a few tips.
1. Increment and decrement
To replace the following implementation:
$article = Article::find($article_id); $article->read_count++; $article->save();
You can do this:
$article = Article::find($article_id); $article->increment('read_count');
The following methods can also be implemented:
Article::find($article_id)->increment('read_count'); Article::find($article_id)->increment('read_count', 10); // +10 Product::find($produce_id)->decrement('stock'); // -1
2. Execute method If method X fails to execute, method Y will be executed."
Example 1 --
findOrFail(): To replace the implementation of the following code:
$user = User::find($id); if (!$user) { abort (404); }
You can write like this:
$user = User::findOrFail($id);
Example 2 --
firstOrCreate(): To replace the implementation of the following code:
$user = User::where('email', $email)->first(); if (!$user) { User::create([ 'email' => $email ]); }
Just write this:
$user = User::firstOrCreate(['email' => $email]);
3 . The model's boot() method
In an Eloquent model, there is a magical place called
boot(), where you can override the default behavior: <pre class="brush:php;toolbar:false">class User extends Model
{
public static function boot()
{
parent::boot();
static::updating(function($model)
{
// 写点日志啥的
// 覆盖一些属性,类似这样 $model->something = transform($something);
});
}
}</pre>
Setting the values of certain fields when creating a model object is probably one of the most popular examples. Let's take a look at what you should do if you want to generate a UUID field when creating a model object.
public static function boot() { parent::boot(); self::creating(function ($model) { $model->uuid = (string)Uuid::generate(); }); }
4. Association with conditions and sorting
General way to define association:
public function users() { return $this->hasMany('App\User'); }
Do you know? You can also add
where or orderBy
?\ on the basis of the above. For example, if you want to associate certain types of users and use the email field to sort, you can Do this:
public function approvedUsers() { return $this->hasMany('App\User')->where('approved', 1)->orderBy('email'); }
5. Model characteristics: time, append, etc.
The Eloquent model has some parameters, using the attribute form of the class. The most commonly used ones are:
class User extends Model { protected $table = 'users'; protected $fillable = ['email', 'password']; // 可以被批量赋值字段,如 User::create() 新增时,可使用字段 protected $dates = ['created_at', 'deleted_at']; // 需要被Carbon维护的字段名 protected $appends = ['field1', 'field2']; // json返回时,附加的字段 }
Not only these, but also:
protected $primaryKey = 'uuid'; // 更换主键 public $incrementing = false; // 设置 不自增长 protected $perPage = 25; // 定义分页每页显示数量(默认15) const CREATED_AT = 'created_at'; const UPDATED_AT = 'updated_at'; //重写 时间字段名 public $timestamps = false; // 设置不需要维护时间字段
There are more. I only listed some interesting features. Please refer to the document abstract Model class for details.
6. Query multiple records by ID
Everyone knows the
find() method, right? <pre class="brush:php;toolbar:false">$user = User::find(1);</pre>
I am very surprised that few people know that this method can accept arrays of multiple IDs as parameters:
$users = User::find([1,2,3]);
7. WhereX
There is an elegant way to This kind of code:
$users = User::where('approved', 1)->get();
is converted into this kind of code:
$users = User::whereApproved(1)->get();
Yes, you read it right, use the field name as a suffix and add it to the end of
where, and it will pass The magic method works. In addition, there are some predefined methods related to time in Eloquent:
User::whereDate('created_at', date('Y-m-d')); User::whereDay('created_at', date('d')); User::whereMonth('created_at', date('m')); User::whereYear('created_at', date('Y'));
8. Sorting by relationship
A more complicated "technique". Do you want to sort forum topics by latest posts? It’s a common requirement to have the most recently updated topics in a forum at the top, right?
First, define a separate relationship for the latest post of the topic:
public function latestPost() { return $this->hasOne(\App\Post::class)->latest(); }
Then, in the controller, we can implement this "magic":
$users = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');
9. Eloquent::when() -- No more using if-else
Many people like to use "if-else" to write query conditions, like this:
if (request('filter_by') == 'likes') { $query->where('likes', '>', request('likes_amount', 0)); } if (request('filter_by') == 'date') { $query->orderBy('created_at', request('ordering_rule', 'desc')); }
There is a better way Method--Use
when()<pre class="brush:php;toolbar:false">$query = Author::query();
$query->when(request('filter_by') == 'likes', function ($q) {
return $q->where('likes', '>', request('likes_amount', 0));
});
$query->when(request('filter_by') == 'date', function ($q) {
return $q->orderBy('created_at', request('ordering_rule', 'desc'));
});</pre>
It may not look very elegant, but its powerful function is to pass parameters:
$query = User::query(); $query->when(request('role', false), function ($q, $role) { return $q->where('role_id', $role); }); $authors = $query->get();
10. One-to-many return Default model object
Suppose there is a situation where you want to display the author of the article, and then the template code is:
{{ $post->author->name }}
But if the author's information is deleted or not set for some reason. The code will return an error such as "property of non-object".
Of course you can handle it like this:
{{ $post->author->name ?? '' }}
You can do this through the Eloquent relationship:
public function author() { return $this->belongsTo('App\Author')->withDefault(); }
In this example, if the text does not have author information,
author () will return an empty App\Author
model object. Furthermore, we can also assign default values to the properties in the default model object.
public function author() { return $this->belongsTo('App\Author')->withDefault([ 'name' => 'Guest Author' ]); }
11. Sorting by assignment function
Imagine you have this code:
function getFullNameAttribute() { return $this->attributes['first_name'] . ' ' . $this->attributes['last_name']; }
Now, you want to sort by "full_name"? Found that there is no The effect:
$clients = Client::orderBy('full_name')->get(); //没有效果
The solution is very simple. We need to sort the results after getting them.
$clients = Client::get()->sortBy('full_name'); // 成功!
Note that the method names are different--it is not orderBy, but sortBy
12. Default sorting under global scope
If you want
User::all() always follow the name
field What about sorting? You can assign it a global scope. Let's go back to boot()
This method we mentioned above: <pre class="brush:php;toolbar:false">protected static function boot()
{
parent::boot();
// 按照 name 正序排序
static::addGlobalScope('order', function (Builder $builder) {
$builder->orderBy('name', 'asc');
});
}</pre>
Extended reading Query scope.
13. 原生查询方法
有时候,我们需要在 Eloquent 语句中添加原生查询。 幸运的是,确实有这样的方法。
// whereRaw $orders = DB::table('orders') ->whereRaw('price > IF(state = "TX", ?, 100)', [200]) ->get(); // havingRaw Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get(); // orderByRaw User::where('created_at', '>', '2016-01-01') ->orderByRaw('(updated_at - created_at) desc') ->get();
14. 复制:复制一行的副本
很简单。说明不是很深入,下面是复制数据库实体(一条数据)的最佳方法:
$task = Tasks::find(1); $newTask = $task->replicate(); $newTask->save();
15. Chunk() 方法之大块数据
与 Eloquent 不完全相关,它更多的关于 Collection (集合),但是对于处理大数据集合,仍然是很有用的。你可以使用 chunk() 将这些数据分割成小数据块
修改前:
$users = User::all(); foreach ($users as $user) { // ...
你可以这样做:
User::chunk(100, function ($users) { foreach ($users as $user) { // ... } });
16. 创建模型时创建额外的东西
我们都知道Artisan命令:
php artisan make:model Company
但是,你知道有三个有用的标记可以为模型生成相关文件吗?
php artisan make:model Company -mcr
-m 将创建一个迁移文件
-c 将创建一个控制器
-r 表示控制器应该是一个资源控制器
17. 调用 save 方法的时候指定 updated_at
你知道 ->save()
方法可以接受参数吗? 我们可以通过传入参数阻止它的默认行为:更新 updated_at
的值为当前时间戳。
$product = Product::find($id); $product->updated_at = '2019-01-01 10:00:00'; $product->save(['timestamps' => false]);
这样,我们成功在 save
时指定了 updated_at
的值。
18. update() 的结果是什么?
你是否想知道这段代码实际上返回什么?
$result = $products->whereNull('category_id')->update(['category_id' => 2]);
我是说,更新操作是在数据库中执行的,但 $result
会包含什么?
答案是受影响的行。 因此如果你想检查多少行受影响, 你不需要额外调用其他任何内容 -- update()
方法会给你返回此数字。
19. 把括号转换成 Eloquent 查询
如果你有个 and
和 or
混合的 SQL 查询,像这样子的:
... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65)
怎么用 Eloquent 来翻译它呢? 下面是一种错误的方式:
$q->where('gender', 'Male'); $q->orWhere('age', '>=', 18); $q->where('gender', 'Female'); $q->orWhere('age', '>=', 65);
顺序就没对。正确的打开方式稍微复杂点,使用闭包作为子查询:
$q->where(function ($query) { $query->where('gender', 'Male') ->where('age', '>=', 18); })->orWhere(function($query) { $query->where('gender', 'Female') ->where('age', '>=', 65); })
20. 复数参数的 orWhere
终于,你可以传递阵列参数给 orWhere()
。平常的方式:
$q->where('a', 1); $q->orWhere('b', 2); $q->orWhere('c', 3);
你可以这样做:
$q->where('a', 1); $q->orWhere(['b' => 2, 'c' => 3]);
我很确定还有更多隐藏的秘诀,但我希望至少上面的其中一些对你来说是新的。
推荐教程:《Laravel教程》
The above is the detailed content of Commonly used Laravel Eloquent essential practical skills. For more information, please follow other related articles on the PHP Chinese website!

ToenhanceengagementandcohesionamongdistributedteamsbeyondZoom,implementthesestrategies:1)Organizevirtualcoffeebreaksforinformalchats,2)UseasynchronoustoolslikeSlackfornon-workdiscussions,3)Introducegamificationwithteamgamesorchallenges,and4)Encourage

Laravel10introducesseveralbreakingchanges:1)ItrequiresPHP8.1orhigher,2)TheRouteServiceProvidernowusesabootmethodforloadingroutes,3)ThewithTimestamps()methodonEloquentrelationshipsisdeprecated,and4)TheRequestclassnowpreferstherules()methodforvalidatio

Tomaintainfocusandmotivationinremotework,createastructuredenvironment,managedigitaldistractions,fostermotivationthroughsocialinteractionsandgoalsetting,maintainwork-lifebalance,anduseappropriatetechnology.1)Setupadedicatedworkspaceandsticktoaroutine.

Tofostercollaborationandtrustinremoteteams,implementthesestrategies:1)Establishregular,structuredcommunicationwithpersonalcheck-ins,2)Usecollaborativetoolsfortransparency,3)Recognizeandcelebrateachievements,and4)Fosteracultureoftrustandadaptability.

Laravel's latest version of the main features include: 1. LaravelOctane improves application performance, 2. Improved model factory support relationships and state definitions, 3. Enhanced Artisan commands, 4. Improved error handling, 5. New Eloquent accessors and modifiers. These features significantly improve development efficiency and application performance, but need to be used with caution to avoid potential problems.

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravelispopularforfull-stackdevelopmentbecauseitoffersaseamlessblendofbackendpowerandfrontendflexibility.1)Itsbackendcapabilities,likeEloquentORM,simplifydatabaseinteractions.2)TheBladetemplatingengineallowsforclean,dynamicHTMLtemplates.3)LaravelMix

Key factors in choosing a video conferencing platform include user interface, security, and functionality. 1) The user interface should be intuitive, such as Zoom. 2) Security needs to be paid attention to, and Microsoft Teams provides end-to-end encryption. 3) Functions need to match requirements, GoogleMeet is suitable for short meetings, and CiscoWebex provides advanced collaboration tools.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
