书香隽秀 - Eloquent ORM
type: channel
link: https://www.huangshuxiu.com/Eloquent-ORM/
description: Eloquent ORM
items: Collections
items: Eloquent: Collections
items: Eloquent ORM

Collections
type: item
date: 2023-05-25T09:00:00+08:00
description: CollectionsIntroductionThe Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We'll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:$collection = collect(['taylor', 'abigail', null])->map(function ($name) { return strtoupper($name); })->reject(function ($name) { return empty($name); });As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. In general, collections are immutable, meaning every Collection method returns an entirely new Collection instance.Creating CollectionsAs mentioned above, the collect helper returns a new Illuminate\Support\Collection instance for the given array. So, creating a collection is as simple as:$collection = collect([1, 2, 3]);The results of Eloquent queries are always returned as Collection instances.Extending CollectionsCollections are "macroable", which allows you to add additional methods to the Collection class at run time. The Illuminate\Support\Collection class' macro method accepts a closure that will be executed when your macro is called. The macro closure may access the collection's other methods via $this, just as if it were a real method of the collection class. For example, the following code adds a toUpper method to the Collection class:use Illuminate\Support\Collection; use Illuminate\Support\Str; Collection::macro('toUpper', function () { return $this->map(function ($value) { return Str::upper($value); }); }); $collection = collect(['first', 'second']); $upper = $collection->toUpper(); // ['FIRST', 'SECOND']Typically, you should declare collection macros in the boot method of a service provider.Macro ArgumentsIf necessary, you may define macros that accept additional arguments:use Illuminate\Support\Collection; use Illuminate\Support\Facades\…

Eloquent: Collections
type: item
date: 2023-05-24T22:55:27+08:00
description: Eloquent: CollectionsIntroductionAll Eloquent methods that return more than one model result will return instances of the Illuminate\Database\Eloquent\Collection class, including results retrieved via the get method or accessed via a relationship. The Eloquent collection object extends Laravel's base collection, so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models. Be sure to review the Laravel collection documentation to learn all about these helpful methods!All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:use App\Models\User; $users = User::where('active', 1)->get(); foreach ($users as $user) { echo $user->name; }However, as previously mentioned, collections are much more powerful than arrays and expose a variety of map / reduce operations that may be chained using an intuitive interface. For example, we may remove all inactive models and then gather the first name for each remaining user:$names = User::all()->reject(function ($user) { return $user->active === false; })->map(function ($user) { return $user->name; });Eloquent Collection ConversionWhile most Eloquent collection methods return a new instance of an Eloquent collection, the collapse, flatten, flip, keys, pluck, and zip methods return a base collection instance. Likewise, if a map operation returns a collection that does not contain any Eloquent models, it will be converted to a base collection instance.Available MethodsAll Eloquent collections extend the base Laravel collection object; therefore, they inherit all of the powerful methods provided by the base collection class.In addition, the Illuminate\Database\Eloquent\Collection class provides a superset of methods to aid with managing your model collections. Most methods return Illuminate\Database\Eloquent\Collection instances; however, some methods, like modelKeys, return an Illuminate\Support\Collection instance.containsdiffexceptfindfr…

Eloquent ORM
type: item
date: 2023-05-24T21:56:00+08:00
description: Eloquent: Getting StartedIntroductionLaravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well.Before getting started, be sure to configure a database connection in your application's config/database.php configuration file. For more information on configuring your database, check out the database configuration documentation.Generating Model ClassesTo get started, let's create an Eloquent model. Models typically live in the app\Models directory and extend the Illuminate\Database\Eloquent\Model class. You may use the make:model Artisan command to generate a new model:php artisan make:model FlightIf you would like to generate a database migration when you generate the model, you may use the --migration or -m option:php artisan make:model Flight --migrationYou may generate various other types of classes when generating a model, such as factories, seeders, policies, controllers, and form requests. In addition, these options may be combined to create multiple classes at once:# Generate a model and a FlightFactory class... php artisan make:model Flight --factory php artisan make:model Flight -f # Generate a model and a FlightSeeder class... php artisan make:model Flight --seed php artisan make:model Flight -s # Generate a model and a FlightController class... php artisan make:model Flight --controller php artisan make:model Flight -c # Generate a model, FlightController resource class, and form request classes... php artisan make:model Flight --controller --resource --requests php artisan make:model Flight -crR # Generate a model and a FlightPolicy class... php artisan make:model Flight --policy # Generate a model and a migration, factory, seeder, and controller.…