Home > Article > PHP Framework > 6 Laravel Eloquent tips to help you improve code readability!
This article compiles and shares six Laravel Eloquent tips that can improve code readability. I hope it will be helpful to everyone!
Eloquent is the ORM used by Laravel by default. Active recording mode is used. Allows you to interact with the database in an easier way. Each individual model represents a table in the database that you can operate on. In this article, we will show you more or less hidden secrets, methods and properties that you may not know about to improve your code.
The snake naming attribute is an interesting attribute. Let's see what the code says:
/** * 指示是否在数组上使用蛇形大小写属性。 * * @var bool */ public static $snakeAttributes = true;
People often use this property incorrectly to change the way the property is accessed. Many people believe that if you change this property, you can easily access the property using camelCase annotations. But in fact, it's not. We strongly recommend you not to use it. When the model is output as an array, just define whether the attribute should be camelCase or SnakeCase.
If you want to base naming on camelCase, we recommend you check out Kirk Bushell's package Eloquence by Kirk Bushell.
If you are If you use Laravel's Eloquent ORM, then this is good news for you. It provides a pagination method out of the box. You may be familiar with writing like this:
$comments = Comment::paginate(20);
Using this method, you can paginate the comment model with 20 entries per page. Change this value to define how many items are displayed per page. If nothing is specified, the default value is applied, which is 15.
Suppose you want your comments to appear in multiple places on your website. There are always 30 comments per page. If you have to pass parameter 30 everywhere, that's a problem. Therefore, you can set new default values directly on the model.
protected $perPage = 30;
Eloquent has a powerful feature called "accessor". This feature allows you to add custom fields to the model or tables that do not exist in the model. It doesn't matter if you use an existing value or define a completely new one, you can always fall back. Below is an example of how the accessor works. Suppose there is a model named user
, we add a FullName accessor to it:
function getFullNameAttribute() { return sprintf('%s %s', $this->first_name, $this->last_name); }
Now you can access the full_name
attribute on the post model, as follows :
User::latest()->first()->full_name;
If an object (such as a collection) is returned, this property will not be attached to the user model. Add the protected$appends
attribute to the model. It accepts an array with one or more fields, which should be automatically appended from now on. Just write it like this:
protected $appends = ['full_name'];
The mutator is the opposite of the getter. You can do really interesting things with it. For example, convert different types of input. Let me tell you in detail. Suppose you want to save a type of time period. Generally, you always save the smallest units possible. In our case it's seconds. For UX reasons, users don't want to enter seconds, like minutes in one place, or hours in another. This can all be resolved quickly.
class Video extends Model { public function setDurationInMinutes($value) { $this->attributes['duration_in_seconds'] = $value * 60; } public function setDurationInHours($value) { $this->attributes['duration_in_seconds'] = $value * 60 * 60; } }
The above code means that you can use a field that does not exist in the data table itself. The
duration_in_minutes field is used in the
model, but in the background, we use duration_in_seconds
to update, or it is possible to use a non-existent field duration_in_hours
. According to this logic, we call it like this in the Controller:
class AnyController { public function store() { $video->update([ 'title' => request('title'), 'duration_in_minutes' => request('duration_in_minutes'), ]); } }
This will save you time in doing calculations in the controller, you can simply use the non-existent column and use ## when performing certain calculations #mutatorMap its result to the correct field.
$comments = Comment::all(); foreach ($comments as $comment) { echo $comment->user->name; }In the above example, we will get all the comment data. Then iterates through the comments and displays the username for each comment. There is nothing wrong with this code and it works fine, but we ran into a problem. Lazy loading now ensures that the query to get the user is only executed when we want to output the username. Welcome to your first N 1 question. Why N 1? N is always the number of reviews and 1 is the query to get the reviews. For example, if we have 500 reviews, then the query to get all reviews is triggered once, and then one query to get the corresponding user-per reviews. So 500 for 1 query. This means that as the number of annotations increases, so does the number of queries. To prevent this, there is a method called eager loading.
$comments = Comment::with('user')->get(); foreach ($comments as $comment) { echo $comment->user->name; }
这会以两个查询结束。第一个查询获取所有注释,第二个查询立即获取所有关联用户。在后台,会发生以下情况(简化版SQL):
SELECT id, user_id, body FROM comments; SELECT name FROM users WHERE user_id IN (1,2,3,4,5...);
不论是 10、500 还是 10000 条评论数据都不重要,我们都依旧只执行两次SQL查询。
好了,你现在已经看到如何使用渴求式加载了。但只限于如何手动使用。你还可以将整个过程自动化,以便某些关联关系总是自动通过渴求式方式加载。为此,需要给模型设定一个属性。
protected $with = [];
我们可以在Comment
model简单设置 protected $with = ['user'];
, 从现在起,user
在任何时候都会自动加载。
我们还有很多种渴求式加载,有仅加载特定列、嵌套即时加载、多个即时加载等等。更多详情请Laravel文档或深入核心。
有的时候需要查询所有的主键 ID, 查询是否复杂并不重要,大多数人可能会像这样做:
User::all()->pluck('id');
这个操作很 nice,但是返回的是一个集合,想要转换成数组的话可以使用 toArray()
。
User::all()->pluck('id')->toArray();
大多数情况下,上面的操作的可以简化成这样:
User::all()->modelKeys();
这种方式返回一个数组。重要的是这个方法并不会总是返回 id
。 顾名思义,他是以数组的形式返回所有模型主键。主键默认是id
,同时也可以在模型中定义主键名。
protected $primaryKey = 'id';
原文地址:https://laravel-news.com/6-eloquent-secrets
译文地址:https://www.php.cn/link/c7decb5ce28209911b545d0b1059c5e3
【相关推荐:laravel视频教程】
The above is the detailed content of 6 Laravel Eloquent tips to help you improve code readability!. For more information, please follow other related articles on the PHP Chinese website!