IMPORTANT: Per accedir als fitxer de subversion: http://acacha.org/svn (sense password). Poc a poc s'aniran migrant els enllaços. Encara però funciona el subversion de la farga però no se sap fins quan... (usuari: prova i la paraula de pas 123456)

Eloquent és un ORM (Object Relational Mapping), és a dir, una llibreria/eina que facilita la creació d'objectes de programació a partir de la informació d'una font de persistència (p.ex. un base de dades). Eloquent és part de Laravel i proporciona una implementació del patró ActiveRecord per tal de treballar amb la base de dades de l'aplicació. Cada taula de la base de dades té el seu corresponent Model (una classe que hereta de la classe Model) i que és la classe utilitzada per interactuar amb la taula.

Passos previs

Vegeu com configurar l'accés a base de dades (fitxer config/database.php) a l'article Laravel Database i també com funcionen les migracions Laravel per a la creació de l'estructura de la base de dades així com les comandes que ofereix artisan per a facilitar la creació de migracions (php artisan migrate) i la creació de models (php artisan Model:create)

Utilitzar eloquent sense Laravel. Paquet de Composer

TODO

Relacions entre taules

http://laravel.com/docs/5.2/eloquent#relationships

Tipus de relacions:

  • One To One
  • One To Many
  • Many To Many
  • Has Many Through
  • Polymorphic Relations
  • Many To Many Polymorphic Relations

Intermediate models: membership example for many-to-many relationship betwwen user and group

Un altre exemple: http://ryantablada.com/post/pivot-tables-vs-pivot-models
Vegeu també pivot table o Associative entity

For people struggling with it, the approach I took was simply to create an intermediary model and access it that way. Instead of thinking of it like user, user_group, and group, I thought of it like user, membership, group.

//user.php

public function memberships(){
 return $this->hasMany('Membership');
}

if you feel safe enough you can do the belongs to many with group directly as well for easy access but it's a bit dangerous when things start to get complex

//membership.php

public function user(){
 return $this->belongsTo('User');
}

public function group(){
return $this->belongsTo('Group');
}

//group.php

public function memberships(){
 return $this->hasMany('Membership');
}

Recursos:

Exemple

Example: Bears, Fish, Trees and Picnics from [1]:

<?php

class Bear extends Eloquent {
    
    // MASS ASSIGNMENT -------------------------------------------------------
    // define which attributes are mass assignable (for security)
    // we only want these 3 attributes able to be filled
    protected $fillable = array('name', 'type', 'danger_level');

    // DEFINE RELATIONSHIPS --------------------------------------------------
    // each bear HAS one fish to eat - ONE TO ONE
    public function fish() {
        return $this->hasOne('Fish'); // this matches the Eloquent model
    }

    // each bear climbs many trees. ONE TO MANY
    public function trees() {
        return $this->hasMany('Tree');
    }

    // each bear BELONGS to many picnic
    // define our pivot table also -->      MANY TO MANY
    public function picnics() {
        return $this->belongsToMany('Picnic', 'bears_picnics', 'bear_id', 'picnic_id');
    }

}

// app/models/Fish.php
<?php

class Fish extends Eloquent {
    
    // MASS ASSIGNMENT -------------------------------------------------------
    // define which attributes are mass assignable (for security)
    // we only want these 3 attributes able to be filled
    protected $fillable = array('weight', 'bear_id');

    // LINK THIS MODEL TO OUR DATABASE TABLE ---------------------------------
    // since the plural of fish isnt what we named our database table we have to define it
    protected $table = 'fish';

    // DEFINE RELATIONSHIPS --------------------------------------------------
    public function bear() {
        return $this->belongsTo('Bear');
    }

}

// app/models/Tree.php
<?php

class Tree extends Eloquent {
    
    // MASS ASSIGNMENT -------------------------------------------------------
    // define which attributes are mass assignable (for security)
    // we only want these 3 attributes able to be filled
    protected $fillable = array('type', 'age', 'bear_id');

    // DEFINE RELATIONSHIPS --------------------------------------------------
    public function bear() {
        return $this->belongsTo('Bear');
    }

}

// app/models/Picnic.php
<?php

class Picnic extends Eloquent {
    
    // MASS ASSIGNMENT -------------------------------------------------------
    // define which attributes are mass assignable (for security)
    // we only want these 3 attributes able to be filled
    protected $fillable = array('name', 'taste_level');

    // DEFINE RELATIONSHIPS --------------------------------------------------
    // define a many to many relationship
    // also call the linking table
    public function bears() {
        return $this->belongsToMany('Bear', 'bears_picnics', 'picnic_id', 'bear_id');
    }

}

Migracions:

Schema::create('bears', function(Blueprint $table)
{
    $table->increments('id');

    $table->string('name');
    $table->string('type');
    $table->integer('danger_level'); // this will be between 1-10

    $table->timestamps();
});

Schema::create('fish', function(Blueprint $table)
{
    $table->increments('id');

    $table->integer('weight'); // we'll use this to demonstrate searching by weight
    $table->integer('bear_id'); // this will contain our foreign key to the bears table

    $table->timestamps();
});

Schema::create('trees', function(Blueprint $table)
{
    $table->increments('id');

    $table->string('type');
    $table->integer('age'); // how old is the tree
    $table->integer('bear_id'); // which bear climbs this tree

    $table->timestamps();
});

Schema::create('picnics', function(Blueprint $table)
{
    $table->increments('id');

    $table->string('name');
    $table->integer('taste_level'); // how tasty is this picnic?

    $table->timestamps();
});

Schema::create('bears_picnics', function(Blueprint $table)
{
    $table->increments('id');

    $table->integer('bear_id'); // the id of the bear
    $table->integer('picnic_id'); // the id of the picnic that this bear is at

    $table->timestamps();
});

Resources:

CRUD Operations

Vegeu també CRUD. Codi font:

https://github.com/scotch-io/laravel-eloquent-guide

Resources:

C of Creating

S'utilitza de la mateixa forma que amb els Laravel Database Seeders:

    // create a bear
    Bear::create(array(
        'name'         => 'Super Cool',
        'type'         => 'Black',
        'danger_level' => 1
    ));

    // alternatively you can create an object, assign values, then save
    $bear               = new Bear;

    $bear->name         = 'Super Cool';
    $bear->type         = 'Black';
    $bear->danger_level = 1;

    // save the bear to the database
    $bear->save();

Una opció alternativa:

 $bear = new Bear();
 $bear->name = "Paquito";
 $bear->type = "Negre";
 $bear->danger_level = "7";
 $bear->save();

Opcions alternatives són:

Exemples:

    // find the bear or create it into the database
    Bear::firstOrCreate(array('name' => 'Lawly'));
 
    // find the bear or instantiate a new instance into the object we want
    $bear = Bear::firstOrNew(array('name' => 'Cerms'));

R of Retrieving

Exemples:

// get all the bears
    $bears = Bear::all();

    // find a specific bear by id
    $bear = Bear::find(1);

    // find a bear by a specific attribute
    $bearLawly = Bear::where('name', '=', 'Lawly')->first();

    // find a bear with danger level greater than 5
    $dangerousBears = Bear::where('danger_level', '>', 5)->get();

First vs Get

Al buscar registres a la base de dades amb get es poden obtenir un o més registres i amb first sempre està limitat a 1 registra (en cas de trobar múltiples s'utilitza el primer)

U of Updating

Exemples:

// let's change the danger level of Lawly to level 10

    // find the bear
    $lawly = Bear::where('name', '=', 'Lawly')->first();

    // change the attribute
    $lawly->danger_level = 10;

    // save to our database
    $lawly->save();

D of Deleting

Exemples:

 // find and delete a record
    $bear = Bear::find(1);
    $bear->delete();

    // delete a record 
    Bear::destroy(1);

    // delete multiple records 
    Bear::destroy(1, 2, 3);

    // find and delete all bears with a danger level over 5
    Bear::where('danger_level', '>', 5)->delete();

Seeding

Vegeu Laravel Seeds

Cheatsheet

Eloquent 
Model::create(array('key' => 'value'));
// Find first matching record by attributes or create
 Model::firstOrCreate(array('key' => 'value'));
// Find first record by attributes or instantiate
 Model::firstOrNew(array('key' => 'value'));
// Create or update a record matching attibutes, and fill with values
 Model::updateOrCreate(array('search_key' => 'search_value'), array('key' => 'value'));
// Fill a model with an array of attributes, beware of mass assignment!
 Model::fill($attributes);
Model::destroy(1);
Model::all();
Model::find(1);
// Find using dual primary key
 Model::find(array('first', 'last'));
// Throw an exception if the lookup fails
 Model::findOrFail(1);
// Find using dual primary key and throw exception if the lookup fails
 Model::findOrFail(array('first', 'last'));
Model::where('foo', '=', 'bar')->get();
Model::where('foo', '=', 'bar')->first();
// dynamic
 Model::whereFoo('bar')->first();
// Throw an exception if the lookup fails
 Model::where('foo', '=', 'bar')->firstOrFail();
Model::where('foo', '=', 'bar')->count();
Model::where('foo', '=', 'bar')->delete();
//Output raw query
 Model::where('foo', '=', 'bar')->toSql();
Model::whereRaw('foo = bar and cars = 2', array(20))->get();
Model::remember(5)->get();
Model::remember(5, 'cache-key-name')->get();
Model::cacheTags('my-tag')->remember(5)->get();
Model::cacheTags(array('my-first-key','my-second-key'))->remember(5)->get();
Model::on('connection-name')->find(1);
Model::with('relation')->get();
Model::all()->take(10);
Model::all()->skip(10);
// Default Eloquent sort is ascendant
 Model::all()->orderBy('column');
Model::all()->orderBy('column','desc');
                
Soft Delete
Model::withTrashed()->where('cars', 2)->get();
// Include the soft deleted models in the results
 Model::withTrashed()->where('cars', 2)->restore();
Model::where('cars', 2)->forceDelete();
// Force the result set to only included soft deletes
 Model::onlyTrashed()->where('cars', 2)->get();
                
Events
Model::creating(function($model){});
Model::created(function($model){});
Model::updating(function($model){});
Model::updated(function($model){});
Model::saving(function($model){});
Model::saved(function($model){});
Model::deleting(function($model){});
Model::deleted(function($model){});
Model::observe(new FooObserver);
                
Eloquent Configuration
// Disables mass assignment exceptions from being thrown from model inserts and updates
 Eloquent::unguard();
// Renables any ability to throw mass assignment exceptions
 Eloquent::reguard();

Vegeu també

Enllaços externs