Tuesday, 21 February 2017

Topic 3 - Eloquent ORM & Relationship

Introduction 


Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

First off u need to declare namespace inside php file and extend eloquent package.


<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

Then, you can list out key working elements and define them in Eloquent ORM 
  • primary key
  • table name
  • mass assignments



Primary Keys

In Eloquent ORM , each model class will assume the tables has default primary key which namely  id . You can override primary key inside model class using $primaryKey attribute.


class Customer extends model{
protected $primaryKey = 'customer_id';  
} 


Table Naming

Basically laravel will use default naming for tables if user did not specific the table name, such that using plural name for the model class. In this case, the class we are using is Customer. Turn out laravel will assume model record in customers table. You can specific table name by define using $table key.

class Customer extends model{
protected $table = 'customer';  
} 



Mass Assignment

You can define model attributes and make mass assignable. Use the $fillable key to make assign array elements.

class Customer extends model{
  protected $fillable = array('customerid','customername'); 
} 


Eloquent Relationship



Activities



1. Create Model Class (Customer, Customer Contact)

2.  Modify App/Routes/Web.php

3. Create View Class using Blade Templating Engine

4. Create Eloquent Relationship


Sample Application


Today's lesson are creating model class that will create a relationship between two  tables to produce a valuable information such that to create bills to customers or to get contact information based on their primary id.

Example of Creating Model Class (Customer)

class Customer extends model
{

protected $table = 'customer';
protected $fillable = array('customerid','customername';

public function customer_contact()
{
return $this->hasMany('App\Customer_contact);
}

}

References

https://laracasts.com/discuss/channels/eloquent/laravel-table-names-are-plural-by-default
https://laravel.com/docs/5.4/eloquent

No comments:

Post a Comment