PHP code example of saintsystems / eloquent-transformable
1. Go to this page and download the library: Download saintsystems/eloquent-transformable library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
saintsystems / eloquent-transformable example snippets
namespace App;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use SaintSystems\Eloquent\Transformable\Transformable;
class Model extends EloquentModel
{
use Transformable;
}
namespace App;
class ActualDatabaseModel extends Model
{
protected $table = 'tbl_Database_Table';
protected $primaryKey = 'PK_Database_ID';
protected $guarded = [];
}
namespace App;
class DesiredDatabaseModel extends ActualDatabaseModel
{
// Desired $primaryKey name (PK_Database_ID is the actual PK in the database)
protected $primaryKey = 'id';
/**
* Transformation Mapping of DB Column Names to desired Eloquent Model Attribute Names
* This variable comes from the SaintSystems\Eloquent\Transformable\Transformable Trait
* used in the base Model.php
* @var array
*/
protected $transform = [
'id' => 'PK_Database_ID',
'name' => 'DB_Name',
'foreign_key_id' => 'FK_DB_Foreign_Key_ID'
]; // TransformationMap;
}
$model = new DesiredDatabaseModel([
'id' => 1,
'name' => 'Name',
'foreign_key_id' => 2
]);
dd($desiredModel->toArray());
/*
Will output the following:
[
'id' => 1,
'name' => 'Name',
'foreign_key_id' => 2
]
*/
// Now, save the model
$model->save();
// Despite using transformed attributes above, the record will still save using the transformed attributes we defined.
// We can even query the model with our desired/transformed column names
$model = new DesiredDatabaseModel::where('name','Joe')->orWhere('name','Judy')->get();
/*
The call above will result in the following query being run:
select *
from "tbl_Database_Table"
where "DB_Name" = 'Joe' or "DB_Name" = 'Judy'
But will come back in the following structure:
[
[
'id' => 1,
'name' => 'Joe',
'foreign_key_id' => 1
],
[
'id' => 2,
'name' => 'Judy',
'foreign_key_id' => 1
]
]
*/
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.