Look at the official document, feel eloquent this ORM basically all frameworks have to do ah, chain call what is not the essence of what, other frameworks have encapsulated a variety of database operations. Why is it that eloquent is laravel very powerful place, what is its characteristic?
Reply content:
Look at the official document, feel eloquent this ORM basically all frameworks have to do ah, chain call what is not the essence of what, other frameworks have encapsulated a variety of database operations. Why is it that eloquent is laravel very powerful place, what is its characteristic?
Simple, efficient, elegant
Basic Features
php
User::first(); // 得到第一个 User 对象User::find(10); // 得到 id = 10 的 User 对象User::where('name', 'john')->first(); // 得到第一个 name = john 的 User 对象User::where('name', 'john')->get(); // 得到 name = john 的 User 对象组User::where('name', 'john')->get()->toArray(); // 得到 name = john 的 User 对象数组Article::where('id', '>=', 10)->where('id', '<=', 20)->orderBy('updated_at', 'desc')->get(); // 得到 Article id 在 10~20 的对象组
Advanced Features
Page out
Back-End Code:
php
return View::make('users')->withUsers(User::paginate(20));
Front-end Code users.blade.php:
php
@foreach ($users as $user)
- id:{{ $user->id }}name:{{ $user->name }}
@endforeach
{{ $users->links() }}
Laravel automatically maintains the component page indicator and links automatically. The paging feature has been completely completed.
Relationship between models
For an example of a one-to-many relationship, get all the articles written by the user ID = 10:
php
class User extends Eloquent { protected $table = 'users'; public function hasManyArticles() { return $this->hasMany('Article', 'user_id', 'id'); }}
Made:
php
$userWithArticles = User::find(10)->hasManyArticles()->get();
Result: The $userWithArticles is a standard user object, plus $userWithArticles->hasmanyarticles's value is the group of objects for all articles written by that user.
More about the relationship between models can be consulted: in-depth understanding of Laravel eloquent (iii)--Model Relationship (association)
Compared to the "modern" PHP framework, the copy is written for the original without the framework/ORM programmer, compared to the direct spell sql,eloquent of course is very powerful in function, but relative to the same genus ActiveRecord propel and mapper/ Proxy mode of the doctrine, there is no qualitative difference.
Additions and deletions to the search will not say, say a few other frames may not have
Pre-loading at 1.relation
n + 1 query problem to reduce ORM
2. Caching
Execute User::find (1) repeatedly, and SQL executes once.
3. Model Viewer
The Observer mode is used to monitor the operation of the model.