Hướng dẫn dùng curso adv trong PHP
Version Show
Eloquent: Getting Started
IntroductionLaravel 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.
Generating Model ClassesTo get started, let's create an Eloquent model. Models typically live in the
If you would like to generate a database migration when you generate the model, you may use the
You 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:
Inspecting ModelsSometimes
it can be difficult to determine all of a model's available attributes and relationships just by skimming its code. Instead, try the
Eloquent Model ConventionsModels generated by the
Table NamesAfter
glancing at the example above, you may have noticed that we did not tell Eloquent which database table corresponds to our If your model's corresponding database table does not fit
this convention, you may manually specify the model's table name by defining a
Primary KeysEloquent will also assume that each model's corresponding database table has a primary key column named
In addition, Eloquent assumes that the primary key is an incrementing integer value,
which means that Eloquent will automatically cast the primary key to an integer. If you wish to use a non-incrementing or a non-numeric primary key you must define a public
If your model's primary key is not an integer, you should define a protected
"Composite" Primary KeysEloquent requires each model to have at least one uniquely identifying "ID" that can serve as its primary key. "Composite" primary keys are not supported by Eloquent models. However, you are free to add additional multi-column, unique indexes to your database tables in addition to the table's uniquely identifying primary key. TimestampsBy default, Eloquent expects
If you need to customize the format of your model's timestamps, set the
If you need to customize the names of the columns used to
store the timestamps, you may define
Database ConnectionsBy default, all Eloquent models will use the default database connection that is configured for your application. If you would like to specify a different connection that should be used when interacting with a particular model, you should define a
Default Attribute ValuesBy default, a newly instantiated model instance
will not contain any attribute values. If you would like to define the default values for some of your model's attributes, you may define an
Retrieving ModelsOnce you have created a model and its associated database table, you are ready to start retrieving data from your database. You can think of each Eloquent model as a powerful
query builder allowing you to fluently query the database table associated with the model. The model's
Building QueriesThe Eloquent
Refreshing ModelsIf you already have an instance
of an Eloquent model that was retrieved from the database, you can "refresh" the model using the
The
CollectionsAs we have seen, Eloquent methods like The Eloquent
In addition to the methods provided by Laravel's base collection class, the Eloquent collection class provides a few extra methods that are specifically intended for interacting with collections of Eloquent models. Since all of Laravel's collections implement PHP's iterable interfaces, you may loop over collections as if they were an array:
Chunking ResultsYour application may run out of memory if you attempt to load tens of thousands of Eloquent records via the The
The first argument passed to the If you are filtering the results of the
Chunking Using Lazy CollectionsThe
If you are filtering the results of the
You may filter the results based on the descending order of the CursorsSimilar to the The
Internally, the
The
Although the Advanced SubqueriesSubquery SelectsEloquent also offers advanced subquery support, which allows you to pull information from related tables in a single query. For example, let's imagine that we have a table of flight Using the subquery functionality available to the query builder's
Subquery OrderingIn addition, the query builder's
Retrieving Single Models / AggregatesIn addition to retrieving all of the records matching a given query, you may also retrieve single records using the
Sometimes
you may wish to perform some other action if no results are found. The
Not Found ExceptionsSometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The
If the
Retrieving Or Creating ModelsThe The
Retrieving AggregatesWhen interacting with Eloquent models, you may also use the
Inserting & Updating ModelsInsertsOf course, when using Eloquent, we don't only need to retrieve models from the database. We also need to insert new
records. Thankfully, Eloquent makes it simple. To insert a new record into the database, you should instantiate a new model instance and set attributes on the model. Then, call the
In this example, we assign the Alternatively, you may use the
However, before using the UpdatesThe
Mass UpdatesUpdates can also be performed against models that match a given query. In this example, all flights that are
The
Examining Attribute ChangesEloquent provides the The
The
The
Mass AssignmentYou may use the
However, before using the A mass assignment vulnerability occurs when a user passes an unexpected HTTP request field and that field changes a column in your database that
you did not expect. For example, a malicious user might send an So, to get started, you should define which model attributes you want to make mass assignable. You may do this using the
Once you have
specified which attributes are mass assignable, you may use the
If you already have a model instance, you may use the
Mass Assignment & JSON ColumnsWhen assigning JSON columns, each column's mass assignable key must be specified in your model's
Allowing Mass AssignmentIf you would like to make all of your attributes mass assignable, you may define your model's
UpsertsOccasionally, you may need to update an existing
model or create a new model if no matching model exists. Like the In the example below, if a flight exists with a
If you would like to perform multiple "upserts" in a single query, then you should use the
Deleting ModelsTo delete a model, you may call the
You may call the
Deleting An Existing Model By Its Primary KeyIn the example above, we are retrieving the model from the database before calling the
Deleting Models Using QueriesOf course, you may build an Eloquent query to delete all models matching your query's criteria. In this example, we will delete all flights that are marked as inactive. Like mass updates, mass deletes will not dispatch model events for the models that are deleted:
Soft DeletingIn addition to actually removing records from your database, Eloquent can also "soft delete" models. When models are soft deleted, they are not actually removed from your database. Instead, a
You should also add the
Now, when you
call the To determine if a given model instance has been soft deleted, you may use the
Restoring Soft Deleted ModelsSometimes you may wish to "un-delete" a soft deleted
model. To restore a soft deleted model, you may call the
You may also use the
The
Permanently Deleting ModelsSometimes you may need to truly remove a model from your database. You may use the
You may also use the
Querying Soft Deleted ModelsIncluding Soft Deleted ModelsAs noted above, soft deleted models will automatically be excluded from query results. However, you may force soft deleted models to be included in a query's results by calling the
The
Retrieving Only Soft Deleted ModelsThe
Pruning ModelsSometimes you may want to periodically delete models that are no longer needed. To accomplish this, you may add the
When marking models as
After configuring your prunable model, you should schedule the
Behind the scenes,
the
If you wish to exclude certain models from being pruned while pruning all other detected models, you may use the
You may test your
Mass PruningWhen models are marked with the
Replicating ModelsYou may create an unsaved copy of an existing model instance using the
To exclude one or more attributes from being replicated to the new model, you may pass an array to the
Query ScopesGlobal ScopesGlobal scopes allow you to add constraints to all queries for a given model. Laravel's own soft delete functionality utilizes global scopes to only retrieve "non-deleted" models from the database. Writing your own global scopes can provide a convenient, easy way to make sure every query for a given model receives certain constraints. Writing Global ScopesWriting a global scope is simple. First, define a class that implements the The
Applying Global ScopesTo assign a global scope to a model, you should override the model's
After adding the scope in the example
above to the
Anonymous Global ScopesEloquent also allows you to define global scopes using closures, which is particularly useful for simple scopes that do not warrant a separate class of their own. When defining a global scope using a closure, you should provide a scope name of your own choosing as the first argument to the
Removing Global ScopesIf you
would like to remove a global scope for a given query, you may use the
Or, if you defined the global scope using a closure, you should pass the string name that you assigned to the global scope:
If you would like to remove several or even all of the query's global scopes, you may use the
Local ScopesLocal scopes allow you to define common
sets of query constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered "popular". To define a scope, prefix an Eloquent model method with Scopes should always return the same query builder instance or
Utilizing A Local ScopeOnce the scope has been defined, you may call the scope methods when querying the model. However, you should not include the
Combining multiple Eloquent model scopes via an
However, since this can be cumbersome, Laravel provides a "higher order"
Dynamic ScopesSometimes you may wish to define a scope that accepts parameters. To get started, just add your additional parameters to your scope method's signature. Scope parameters should be defined after the
Once the expected arguments have been added to your scope method's signature, you may pass the arguments when calling the scope:
Comparing ModelsSometimes you may need to determine if two models are the "same" or
not. The
The
Events
Eloquent models dispatch several events, allowing you to hook into the following moments in a model's lifecycle: The To start listening to model events, define a
After defining and mapping your Eloquent events, you may use event listeners to handle the events.
Using ClosuresInstead of using custom event classes, you may register closures that execute when various model events are dispatched. Typically, you should register these closures in the
If needed, you may utilize queueable anonymous event listeners when registering model events. This will instruct Laravel to execute the model event listener in the background using your application's queue:
ObserversDefining ObserversIf you are listening for many events on a given model, you may use observers to group all of your listeners into a single class. Observer classes have method names which reflect the Eloquent events you wish to listen for. Each of these
methods receives the affected model as their only argument. The
This command will place the new observer in your
To register an observer, you need to call the
Alternatively, you may list your observers within an
Observers & Database TransactionsWhen models
are being created within a database transaction, you may want to instruct an observer to only execute its event handlers after the database transaction is committed. You may accomplish this by defining an
Muting EventsYou may occasionally need to temporarily "mute" all events fired by a model. You may achieve this using the
Saving A Single Model Without EventsSometimes you may wish to "save" a given model without dispatching any events. You may accomplish this using the
You may also "update", "delete", "soft delete", "restore", and "replicate" a given model without dispatching any events: |