“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

There is no superior or inferior martial arts in the world, only those who practice martial arts are strong or weak.

Eloquent Model: 1. Eloquent Model: Eloquent Model: 1.

Use advanced techniques for the Laravel Eloquent model

Rename column names

Eloquent Query Builder, you can use AS to rename column names for output, as:

$users = DB::table('users')->select('name', 'email as my_email')->get();
Copy the code

Map Query results

After the Eloquent query, you can use the map() function in Collections to modify rows.

$users = User::where('role_id', 1)->get()->map(function (User $user) {
    $user->some_column = some_function($user);
    return $user;
});
Copy the code

Array map() :

$userIds = array_map(function ($value) { return ['userid' => $value]; }, $appointmentsUserIds); [' userID '= XXXX],['userid'= XXXX],]Copy the code

Quick sort by time field

Not recommended:

User::orderBy('created_at', 'desc')->get();
Copy the code

It is recommended to use the following methods for faster execution:

User::latest()->get();
Copy the code

By default, latest() is sorted descending by created_AT.

There is a simple inverse method called oldest(), which sorts by created_at ascending:

User::oldest()->get();
Copy the code

You can specify a time field for sorting

$lastUpdatedUser = User::latest('updated_at')->first();
Copy the code

Raw SQL query

Using SQL raw queries like whereRaw() and doing some database-specific calculations directly in the query, rather than in Laravel, usually results are faster.

For example, a user who is still active more than 10 days after the registration can use the following code:

User::where('active', 1) ->whereRaw('TIMESTAMPDIFF(DAY, created_at, updated_at) > ? ', 10) ->get();Copy the code

Multiple range query

Combine and chain query ranges in Eloquent, and use multiple ranges in a query.

Model:

public function scopeActive($query) {
    return $query->where('active', 1);
}

public function scopeRegisteredWithinDays($query, $days) {
    return $query->where('created_at', '>=', now()->subDays($days));
}
Copy the code

Used in controller:

$users = User::registeredWithinDays(10)->active()->get();
Copy the code

No need to convert Carbon

If whereDate() is used to query today’s records, you can use Carbon’s now() method, which automatically converts the query to a date, without specifying ->toDateString() :

$todayUsers = User::whereDate('created_at', now()->toDateString())->get(); $todayUsers = User::whereDate('created_at', now())->get();Copy the code

Never update a field

If you have a database field that needs to be updated only once, you can use the Eloquent modifier to do so:

Class User extends Model {public function setEmailAttribute($value) {if ($this->email) {return; } $this->attributes['email'] = $value; }}Copy the code

Find () Queries multiple pieces of data

Find () can query for more than one piece of data, and returns a collection of results when passed multiple ids:

Eloquent Model $user = user ::find(1); Eloquent Collection $users = User::find([1,2,3]);Copy the code

Find () restriction field

Find () specifies which fields to return in the case of multiple queries:

$user = user ::find(1, ['first_name', 'email']); $user = user ::find(1, ['first_name', 'email']); $users = User::find([1,2,3], ['first_name', 'email']);Copy the code

Welcome to the interactive

Welcome everyone to like attention, if you have any good suggestions, welcome to the comment section