edit

Skytells Framework Eloquents


Introduction

The Eloquent ORM included with Skytells Framework provides a beautiful, simple ActiveRecord implementation for working with your database.
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.

Checking ORM Configuration

Before getting started,
be sure to configure a database connection in Application/Misc/Config/Databases.php
And $Skytells['ORM'] is set to TRUE

For more information on configuring your database, check out the documentation.

Creating Eloquents

All Eloquents must be stored in this folder.

1
Application/Resources/Models/Eloquents

Create a file inside the mentioned path to be like :

1
Application/Resources/Models/Eloquents/Users.php

Put with the following code in your model.

1
2
3
4
5
6
7
8
<?php
use Skytells\Events\Dispatcher;
use Skytells\Container\Container;
use Skytells\Database\Capsule\Manager as Capsule;

 Class Users extends Skytells\Database\Eloquent\Model {
  protected $table = 'users';
 }

Okay!

Now your Eloquent has been successfully linked to the ORM system.

In case of working with Multiple Databases:
Identify the database name before table name in $table variable.

To be like :

1
2
3
4
5
6
7
8
<?php
use Skytells\Events\Dispatcher;
use Skytells\Container\Container;
use Skytells\Database\Capsule\Manager as Capsule;

 Class Users extends Skytells\Database\Eloquent\Model {
  protected $table = 'database.users'; // <-- SEE {DB}.{TABLE}
 }

Loading Eloquents in Models

Now get back to your model, and load the Eloquent

Open your model :

1
Application/Resources/Models/MyModel.php

In the model's construct() function put the following code :

1
2
<?php
$this->AddEloquent('Users');

Eloquent Loaded

Now the Users Eloquent has been loaded to your model and its ready for use.

Now lets move on to learn how to use the Users Eloquent.


Using Eloquents

Now lets start learning how to use Eloquents.

Retrieving ORM Models

Once you have created a model and its associated database table, you are ready to start retrieving data from your database.
Think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model.

For example, Open your Model and put this code :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?php
use Skytells\Events\Dispatcher;
use Skytells\Container\Container;
use Skytells\Database\Capsule\Manager as Capsule;

Class HomeModel extends Model {
  function __construct($Ref = '') {
     parent::__construct();
     $this->AddEloquent('Users');
     $this->Connect('Default') // Connect to db.1

  }

  function getDataFromEloquent() {
    $Users = Users::all();
    // Now the users array contains the entire data
    // which stored in database table (Users)
  }
}

Adding Additional Constraints

The Eloquent all method will return all of the results in the model's table. Since each Eloquent model serves as a query builder, you may also add constraints to queries, and then use the get method to retrieve the results:

1
2
3
4
5
<?php
$Users = Users::where('active', 1)
               ->orderBy('name', 'desc')
               ->take(10)
               ->get();

Note

Since Eloquent models are query builders, you should review all of the methods available on the query builder. You may use any of these methods in your Eloquent queries.

Collections

For Eloquent methods like all and get which retrieve multiple results, an instance of Skytells\Database\Eloquent\Collection will be returned.

The Collection class provides a variety of helpful methods for working with your Eloquent results:

1
2
3
<?php
$Users = $Users->reject(function ($User) {
        return $User->name; });

Of course, you may also simply loop over the collection like an array:

1
2
3
4
<?php
 foreach ($Users as $User) {
        echo $User->name;
 }

Chunking Results

If you need to process thousands of Eloquent records, use the chunk command.

The chunk method will retrieve a "chunk" of Eloquent models, feeding them to a given Closure for processing.
Using the chunk method will conserve memory when working with large result sets:

1
2
3
4
5
6
<?php
Users::chunk(200, function ($Users) {
    foreach ($Users as $User) {
        //
    }
});

The first argument passed to the method is the number of records you wish to receive per "chunk".
The Closure passed as the second argument will be called for each chunk that is retrieved from the database.
A database query will be executed to retrieve each chunk of records passed to the Closure.

Using Cursors

The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query.
When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage:

1
2
3
4
<?php
foreach (Users::where('foo', 'bar')->cursor() as $user) {
    //
}

Retrieving Single Models / Aggregates

Of course, in addition to retrieving all of the records for a given table, you may also retrieve single records using find or first.
Instead of returning a collection of models, these methods return a single model instance:

1
2
3
<?php
// Retrieve a model by its primary key...
$User = Users::find(1);
1
2
3
<?php
// Retrieve the first model matching the query constraints...
$User = Users::where('active', 1)->first();

You may also call the find method with an array of primary keys, which will return a collection of the matching records:

1
2
<?php
$Users = Users::find([1, 2, 3]);
Not Found Exceptions

Sometimes you may wish to throw an exception if a model is not found.
This is particularly useful in routes or controllers.
The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Skytells\Database\Eloquent\ModelNotFoundException will be thrown:

1
2
3
4
<?php
$model = Users::findOrFail(1);

$model = Users::where('legs', '>', 100)->firstOrFail();

If the exception is not caught, a 404 HTTP response is automatically sent back to the user.
It is not necessary to write explicit checks to return 404 responses when using these methods:

1
2
3
4
5
6
<?php
Router::map('GET|POST', '/api/users/[i:id]', function($id) {
  Boot::Controller('Home', 'index', Array("id" => $id));
  // Boot Controller which contains the ORM function following :
  // return Users::findOrFail($id);
  });

Retrieving Aggregates

You may also use the count, sum, max, and other aggregate methods provided by the query builder. These methods return the appropriate scalar value instead of a full model instance:

1
2
3
4
<?php
$count = Users::where('active', 1)->count();

$max = Users::where('active', 1)->max('price');

Inserting & Updating Models

Inserts

To create a new record in the database, simply create a new model instance, set attributes on the model, then call the save method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php
class UsersController extends Controller
{

    public function store(Request $request)
    {
        $this->load->model('{MODEL}', $this)
        // Validate the request...
        $user = new Users;
        $user->name = $request->name;
        $user->save();
    }
}

In this example, we simply assign the name parameter from the incoming HTTP request to the name attribute of the Users model instance.

When we call the save method, a record will be inserted into the database.

The created_at and updated_at timestamps will automatically be set when the save method is called, so there is no need to set them manually.

Updates

The save method may also be used to update models that already exist in the database.
To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value:

1
2
3
4
5
6
<?php
$user = Users::find(1);

$user->name = 'New User Name';

$user->save();

Mass Updates

Updates can also be performed against any number of models that match a given query. In this example, all users that are active and have a city of San Diego will be marked as is_active:

1
2
3
4
<?php
Users::where('active', 1)
          ->where('city', 'San Diego')
          ->update(['is_active' => 1]);

The update method expects an array of column and value pairs representing the columns that should be updated.

Note

When issuing a mass update via Eloquent, the saved and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.

Available Methods

The Base Collection All Eloquent collections extend the base Skytells collection object; therefore, they inherit all of the powerful methods provided by the base collection class:

s s s s s
all average avg chunk collapse combine
concat contains containsStrict count crossJoin dd
diff partition diffKeys dump each eachSpread
every except merge filter first flatMap
flatten flip forget min forPage get
groupBy has implode intersect isEmpty isNotEmpty
keyBy keys last map nth only
mapInto mapSpread mapToGroups mapWithKeys max median
pad pipe partition mode random reduce
pluck pop prepend pull push put
reject reverse search shift shuffle slice
sort sortBy sortByDesc splice split sum
take tap toArray toJson transform union
unique uniqueStrict unless values when where
whereStrict whereIn whereInStrict whereNotIn whereNotInStrict zip