Introduced
Laravel's eloquent ORM provides a beautiful, concise ActiveRecord implementation to interact with the database. Each database table interacts with a corresponding "model".
Before you start, remember to configure the database connection in the config/database.php.
Basic usage
Let's start with building a eloquent model. Models are usually placed in the app directory, but you can place them anywhere, as long as they can be automatically loaded via Composer.json. All eloquent models are inherited from the Illuminate\database\eloquent\model.
For example I put under App/models, then the configuration in Composer.json is as follows:
"Autoload-dev": { "classmap": ["tests/testcase.php", "App/models"]},
1. Create [model]
Manually Create
Create a new file under App/models logo.php
Command creation
PHP Artisan Make:model User
The advantage of command creation is that the corresponding database migration files are generated at the same time under Database/migrations.
Note that we did not tell eloquent which database table the user model would use. If not specified, the system automatically corresponds to a database table named "Lowercase plural pattern of class name". So, in the example above, eloquent would assume that the User model would present the data to the Users database table. You can also define a table property in your class to customize the database tables that you want to correspond to. Class Logo extends Model { protected $table = ' My_logo ';}
Note: Eloquent also assumes that each database table has a primary key that has a field name of ID. You can override this by defining the PrimaryKey property in the class. Similarly, you can define the connection property to specify that the model connects to the specified database connection.
Once you have defined the model, you can add and retrieve data from the database table. Note By default, you need to have updated_at and created_at two fields in the database table. If you do not want to set or automatically update these two fields, set the $timestamps property in the class to false. Public $timestamps = false;
2. Using the [model]
Ways to use the model
Remove all records: $logos = Logo::all ();
Take a piece of data based on the primary key: $logos = Logo::find (1);
Split query: The first parameter that is passed to the method represents the number of data to be fetched each time "split". The closing function of the second parameter is called every time the data is fetched.
User::chunk ($, function ($users) { //query 200 foreach ($users as $user) { // }});
Other methods are not listed, you can access: [Eloquent ORM] (http://laravel-china.org/docs/5.0/eloquent)
You can also use the Whereraw method if there is no way to produce a query statement using a fluent interface: $users = User::whereraw (' Age >? and votes = + ', [+])->get ();
Soft Delete
When a model is deleted by a soft-delete method, the data in the model is not really removed from the database. Instead, the Deleted_at timestamp is set. For the model to use the soft-delete feature, simply add the softdeletingtrait to the model class:
Use Illuminate\database\eloquent\softdeletes;class User extends Model {use softdeletes; protected $dates = [' Deleted_at '];}
To add the Deleted_at field to a database table, you can use the Softdeletes method in the migration file:
$table->softdeletes ();
Now when you call the Delete method using the model, the Deleted_at field is updated to the current timestamp. When querying a model that uses the soft-delete feature, model data that is "deleted" does not appear in the query results.
The normal query method can only query data that is Deleted_at null, that is, data that is not deleted/valid. To force model data that has been soft-deleted to appear in the query results, use the Withtrashed method at query time: $users = user::withtrashed ()->where (' account_id ', 1)->get ();
If you want to query only soft-deleted model data, you can use the Onlytrashed method: $users = user::onlytrashed ()->where (' account_id ', 1)->get ();
To restore the soft-deleted model data, use the Restore method: $user->restore ();
You can also use RESTORE with query statements: User::withtrashed ()->where (' account_id ', 1)->restore ();
If you want to really delete from the model database, use the Forcedelete method: $user->forcedelete ();
To confirm that the model is soft-deleted, you can use the trashed method: if ($user->trashed ()) { //}
Scope Query
Defining a Scope query
Scope queries allow you to easily reuse the query logic of your model. To set a range query, simply define a model method with the scope prefix:
Class User extends Model {public function scopepopular ($query) { return $query->where (' votes ', ' > ', 100); } Public Function Scopewomen ($query) { return $query->wheregender (' W ');} }
Using range queries
$users = User::p opular ()->women ()->orderby (' Created_at ')->get ();
Dynamic Range Query
Sometimes you might want to define a range query method that accepts parameters. Just add the parameters to the method:
Class User extends Model {public function Scopeoftype ($query, $type) { return $query->wheretype ($type);} }
The parameter values are then passed to the range Query method call:
$users = User::oftype (' member ')->get ();
3. Association
One
Define a one-to-one association
One-to-a-correlation is a very basic association. For example, a User model would correspond to a Phone. In eloquent, you can define the association as follows:
Class User extends Model {public function phone () { return $this->hasone (' App\phone ');} }
The first parameter passed to the HasOne method is the class name of the associated model. Once you have defined the association, you can use the dynamic properties of eloquent to get the associated object:
$phone = User::find (1)->phone;
SQL executes the following statement:
SELECT * from the users where id = 1select * from phones where user_id = 1
Note that the eloquent assumes the corresponding relational model database table, and the foreign key name is based on the model name. In this example, the default Phone model database table takes user_id as the foreign key. If you want to change this default, you can pass in the second parameter into the HasOne method. Further, you can pass in the third parameter, specifying which field the associated foreign key corresponds to itself: return $this->hasone (' App\phone ', ' Foreign_key '); return $this->hasone (' App\phone ', ' foreign_key ', ' Local_key ') );
To define relative associations
To define relative associations in the Phone model, you can use the Belongsto method:
Class Phone extends Model {public function user () { return $this->belongsto (' App\user ');} }
In the example above, eloquent defaults to querying the association using the user_id field of the Phones database table. If you want to specify a foreign key field yourself, you can pass in the second parameter in the Belongsto method:
Class Phone extends Model {public function user () { return $this->belongsto (' App\user ', ' Local_key ');} }
In addition, you can pass in the third parameter to specify which field of the upper-level database table to refer to:
Class Phone extends Model {public function user () { return $this->belongsto (' App\user ', ' Local_key ', ' Parent _key ');} }
One-to-many
Define a one-to-many association
A one-to-many association example, a blog post might have "lots" of comments. You can define associations like this:
Class Post extends Model {public function comments () { return $this->hasmany (' app\comment ');} }
You can now get comments on the article via Dynamic properties:
$comments = Post::find (1)->comments;
If you need to add more conditional restrictions, you can use the chained query condition method after calling the comments method:
$comments = Post::find (1)->comments ()->where (' title ', ' = ', ' foo ')->first ();
Similarly, you can pass the second parameter to the Hasmany method to change the default foreign key name. And, as with the HasOne Association, you can specify the corresponding field for itself:
return $this->hasmany (' app\comment ', ' Foreign_key '); return $this->hasmany (' app\comment ', ' foreign_key ', ' Local_key ');
To define relative associations
To define the corresponding association in the Comment model, you can use the Belongsto method:
Class Comment extends Model {public function post () { return $this->belongsto (' App\post ');} }
Many-to-many
Define many-to-many associations
Many-to-many associations are more complex. Examples of such associations are that a user may have many identities (roles), and one identity may be available to many users. For example, many users are "managers". Many-to-many associations require three database tables: Users, roles, and Role_user. The Role_user hub table is named after the associated two model database tables, named in alphabetical order, and the pivot table should have user_id and role_id fields.
You can use the Belongstomany method to define a many-to-many relationship:
Class User extends Model {public function roles () { return $this->belongstomany (' App\role ');} } Class Role extends Model {public function users () { return $this->belongstomany (' App\user ');} }
Now we can get roles from the User model:
$roles = User::find (1)->roles;
If you do not want to use the default Hub database table naming method, you can pass the database table name as the second parameter of the Belongstomany method:
return $this->belongstomany (' app\role ', ' user_roles ');
You can also change the default associated field name:
return $this->belongstomany (' app\role ', ' user_roles ', ' user_id ', ' foo_id ');
has many Through far layer one-to-many association
The "far-one-to-many association" provides a convenient and short way to get the association of a far layer through a multi-layer association. For example, a country model might be associated with many Posts models through the Users. The relationships between database tables may look like this:
Countries Id-integer name-stringusers id-integer country_id-integer name-stringposts Id-integer User_id-integer title-string
Although the posts database table itself does not have a country_id field, the Hasmanythrough method allows us to use the $country->posts to get country posts. We can define the following associations:
Class Country extends Model {public function posts () { return $this->hasmanythrough (' app\post ', ' App\user ') ; }}
If you want to manually specify an associated field name, you can pass in the third and fourth parameters into the method:
Class Country extends Model {public function posts () { return $this->hasmanythrough (' app\post ', ' app\ User ', ' country_id ', ' user_id ');} }
Correlation Query
Query based on association criteria
When you get model data, you may want to use the correlation model as a query restriction. For example, you might want to get all the "at least one comment" blog post. You can use the has method to achieve the purpose:
$posts = Post::has (' comments ')->get ();
You can also specify operators and quantities:
$posts = Post::has (' comments ', ' >= ', 3)->get ();
You can also use the form "dot" to get a nested have declaration:
$posts = Post::has (' comments.votes ')->get ();
If you want more advanced usage, you can use the Wherehas and Orwherehas methods to set the "where" condition in the has query:
$posts = Post::wherehas (' Comments ', function ($q) { $q->where (' content ', ' like ', ' foo% ');}) ->get ();
Dynamic Properties
Eloquent can get associated objects through dynamic properties. Eloquent automatically makes association queries, and it's smart to know that you should use get (used in a one-to-many association) or first (in one-to-one association) methods. objects can be obtained through dynamic properties with the same name as the associated method. For example, the following model object $phone:
Class Phone extends Model {public function user () { return $this->belongsto (' App\user ');} } $phone = Phone::find (1);
You can not print the user's Email:echo as follows $phone->user ()->first ()->email;
and can be abbreviated as follows: Echo $phone->user->email;
If you get many associated objects, the Illuminate\database\eloquent\collection object is returned. Pre-loading
Pre-loading is used to reduce the N + 1 query problem. For example, a book model data is associated to a Author. The association is defined as follows:
Class Book extends Model {public function author () { return $this->belongsto (' App\author ');} }
Now consider the following code:
foreach (Book::all () as $book) { echo $book->author->name;}
The above loop executes a query to retrieve the books on all the database tables, but each book executes a query to get the author. So if we have 25 books, we will make 26 queries.
Fortunately, we can use pre-loading to reduce the number of queries in large numbers. Use the With method to specify the associated object that you want to preload:
foreach (Book::with (' author ')->get () as $book) {echo $book->author->name;}
Now, the above loop will only execute two queries in total:
SELECT * FROM Booksselect * FROM authors where ID in (1, 2, 3, 4, 5, ...)
Using pre-loading can greatly improve the performance of the program.
Of course, you can also load multiple associations at the same time:
$books = Book::with (' Author ', ' publisher ')->get ();
Pre-loading condition limits
Sometimes you may want to preload the association, and you want to specify the query limit at load time. Here's an example:
$users = User::with ([' posts ' = function ($query) { $query->where (' title ', ' Like ', '%first% ');}]) ->get ();
In the above example, we preload the user's posts association and restrict the title field of the post to include "first".
Of course, pre-loaded closed functions may not only be conditional, but can also be sorted:
$users = User::with ([' posts ' = function ($query) { $query->orderby (' created_at ', ' desc ');}]) ->get ();
New Correlation model
Attach an association model
You will often need to add a new affiliate model. For example, add a comment to post. In addition to manually setting the POST_ID foreign key for the model,
You can also add the associated comment from the upper Post model:
$comment = new Comment ([' message ' = ' A new comment. ']); $post = Post::find (1); $comment = $post->comments ()->save ($comment);
In the above example, the post_id field in the new comment model is automatically set.
If you want to add many associated models at the same time:
$comments = [ new Comment ([' message ' = ' A new Comment. ']), new Comment ([' message ' = ' another Comment. ']), new Comment ([' message ' = ' "the latest Comment. '])]; $post = Post::find (1); $post->comments ()->savemany ($comments);
Dependent Association model (belongs to)
You can use the Associate method when you want to update the Belongsto Association. This method sets the foreign key of the sub-model:
$account = Account::find, $user->account ()->associate ($account), $user->save ();
New many-to-many association models (many to many)
You can also add many-to-many correlation models. Let's continue with the user and Role model as an example. We can simply attach the roles to a user by using the Attach method:
Attach many-to-many models
$user = User::find (1), $user->roles ()->attach (1);
You can also pass in an array of attributes to exist in the hub table:
$user->roles ()->attach (1, [' expires ', ' = $expires]);
Of course, there are attach methods that have the opposite detach method:
$user->roles ()->detach (1);
Both attach and detach can accept an array of IDs as parameters:
$user = User::find (1); $user->roles ()->detach ([1, 2, 3]); $user->roles ()->attach ([1 = [' attribute1 ' = > ' value1 '], 2, 3]);
Use the Sync method to attach more than one multiple-to-many association at a time
You can also attach an association model using the sync method. The Sync method saves the association to the pivot table based on the ID array. When the association is appended, the model in the pivot table is only associated with the ID in the ID array:
$user->roles ()->sync ([1, 2, 3]);
Add additional data to the hub table when Sync
You can also add data from other fields when you add each ID to the pivot table:
$user->roles ()->sync ([1 = [' Expires ' = true]]);
Sometimes you might want to use a command to attach an association while building the new model data. You can use the Save method to accomplish the purpose:
$role = new Role ([' name ' = ' Editor ']); User::find (1)->roles ()->save ($role);
In the above example, the new Role model object is associated with the user model at the same time as stored. You can also pass in an array of attributes to add data to the associated database table:
User::find (1)->roles ()->save ($role, [' Expires ' = ' + $expires]);