Laravel-Model
Eloquent ORM is Object Relational Mapper that allows us to define the relationship with the model, so once a relationship is defined, we can perform database manipulation without explicit query.
Type
- One to One
- One to Many
- Many to Many
- HasManyThrough
- Polymorphic one to one/one to many
Implementation
- Install laravel
- create a new database in MySQL (blog)
- update DB details in config/database.php
one to one relation
Example :- Schema
- Table :- Post
- Fields :- id, title, date
- Table 2 :- Post_content
- Fields :- id, post_id, content
In the above tables post_id is the foreign_key of Post_Content, create the relation between these tables, first, we need to create the model: –
BlogModel class Post extends Eloquent { protected $table='post'; public function post_content() { return $this->hasOne('Content'); } } ContentModel class Content extends Eloquent { protected $table= 'post_content'; }
For access data we can use $blog->blog_content
One to Many
In this relation each blog there is only a single author and a single author can have many posts (one-to-*).
- Table :- Post
- Fields :- id, date, author_id, title
- Table 2 :- Blog_Author
- Fields :- id, author_name
For the above tables let’s establish a one-to-* relation using the hasMany function.
Using $blog_author->post we get all the posts of a single author. Here we need to get the author details of a single post, and for each post, there is a single author, within the Post model including belongsTo relation.
With the Data of Post table, we get the details of an author using $post->author->author_name
we can loop through all the posts of an author using $author->post In Author
Blog_Author class Blog_Author extends Eloquent { protected $table='blog_author'; public function post(){ return $this->hasMany('Post'); } } Post class Post extends Eloquent { protected $table='post'; public function author(){ return $this->belongsTo('Blog_Autho','author_id'); } }
Many To Many
There is, each post can have many tags and each tag can have many posts.
- Table :- Tag
- Fields :- id, name
- Table 2 :- post_tag
- Fields :- post_id,tag_id,author_id
To establish the relation, we use the belongsTo function
public function tags() { return belongsToMany('tag'); } public function post() { return belongsToMany('Post'); }
Laravel Model Relationships
Using the above methods can read data, while creating a new post we need to insert data to Post, Content, Author, etc. we can perform this using query builder save()
$post = Post::create(array('title' => Input::get('title')); // insert into table post $text = Text::create(array('text' => Input::get('text')); // insert into table content $post->text()->save($text);
Conclusion
This article includes the fundamentals of the Eloquent ORM model. Laravel Eloquent ORM implementation is really fast and the interaction with the database is very simple.