Table of Contents
Pagination
Add custom values ​​in the model" >Add custom values ​​in the model
Add a mutator (property setter) for the non-existent column
modelKeys 方法
Home PHP Framework Laravel 6 Laravel Eloquent tips to help you improve code readability!

6 Laravel Eloquent tips to help you improve code readability!

Nov 15, 2022 pm 08:07 PM
php laravel

This article compiles and shares six Laravel Eloquent tips that can improve code readability. I hope it will be helpful to everyone!

6 Laravel Eloquent tips to help you improve code readability!

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.

Snake naming attribute

The snake naming attribute is an interesting attribute. Let's see what the code says:

/**
 * 指示是否在数组上使用蛇形大小写属性。
 *
 * @var bool
 */
public static $snakeAttributes = true;
Copy after login

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.

Pagination

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);
Copy after login

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;
Copy after login

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);
}
Copy after login

Now you can access the full_name attribute on the post model, as follows :

User::latest()->first()->full_name;
Copy after login

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'];
Copy after login

Add a mutator (property setter) for the non-existent column

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;
    }
}
Copy after login

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'),
        ]);
    }
}
Copy after login

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.

Eager loading: with $with

Let’s talk about relationships. By default, Laravel uses lazy loading. What does this mean in terms of relationships? The advantage of lazy loading is that it can save memory, because not all data needs to be retained, and we can load data when needed. As follows:

$comments = Comment::all();
foreach ($comments as $comment) {
    echo $comment->user->name;
}
Copy after login

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;
}
Copy after login

这会以两个查询结束。第一个查询获取所有注释,第二个查询立即获取所有关联用户。在后台,会发生以下情况(简化版SQL):

SELECT id, user_id, body FROM comments;
SELECT name FROM users WHERE user_id IN (1,2,3,4,5...);
Copy after login

不论是 10、500 还是 10000 条评论数据都不重要,我们都依旧只执行两次SQL查询。

好了,你现在已经看到如何使用渴求式加载了。但只限于如何手动使用。你还可以将整个过程自动化,以便某些关联关系总是自动通过渴求式方式加载。为此,需要给模型设定一个属性。

protected $with = [];
Copy after login

我们可以在Comment model简单设置 protected $with = ['user'];, 从现在起,user在任何时候都会自动加载。

我们还有很多种渴求式加载,有仅加载特定列、嵌套即时加载、多个即时加载等等。更多详情请Laravel文档或深入核心。

modelKeys 方法

有的时候需要查询所有的主键 ID, 查询是否复杂并不重要,大多数人可能会像这样做:

User::all()->pluck('id');
Copy after login

这个操作很 nice,但是返回的是一个集合,想要转换成数组的话可以使用 toArray()

User::all()->pluck('id')->toArray();
Copy after login

大多数情况下,上面的操作的可以简化成这样:

User::all()->modelKeys();
Copy after login

这种方式返回一个数组。重要的是这个方法并不会总是返回 id。 顾名思义,他是以数组的形式返回所有模型主键。主键默认是id,同时也可以在模型中定义主键名。

protected $primaryKey = 'id';
Copy after login

原文地址: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!

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

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

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)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

See all articles