PHP code example of daycry / relations

1. Go to this page and download the library: Download daycry/relations 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/ */

    

daycry / relations example snippets


	use \Daycry\Relations\Traits\ModelTrait

	protected $with = 'groups';
	// or
	protected $with = ['groups', 'permissions'];

$users = $userModel->with('groups')->findAll();
foreach ($users as $userEntity)
{
	echo "User {$user->name} has " . count($user->groups) . " groups.";
...

	use \Daycry\Relations\Traits\EntityTrait
	
	protected $table      = 'users';
	protected $primaryKey = 'id';

	$user = $userModel->find(1);
	
	foreach ($user->groups as $group)
	{
		echo $group->name;
	}

	$user->addGroup(3);
	
	if ($user->hasGroups([1, 3]))
	{
		echo 'allowed!';
	}
	
	$user->setGroups([]);

use Daycry\Relations\Contracts\RelatableInterface;
class UserModel extends Model implements RelatableInterface { use ModelTrait; }
class User extends Entity implements RelatableInterface { use EntityTrait; }

protected function afterRelations(array &$rows, array $loadedTables): void { /* mutate or log */ }
protected function afterEntityRelations(string $table, mixed &$result, bool $keysOnly): void { /* transform */ }

$metrics = \Daycry\Relations\Traits\BaseTrait::getRelationMetrics();
// ['calls' => 12, 'tables' => ['groups' => 5, 'permissions' => 7]]
\Daycry\Relations\Traits\BaseTrait::getRelationMetrics(true); // resets

$model = new UserModel();
$names = $model->listRelations();
// p.ej: ['groups','permissions','profile']

$details = $model->relationDetails(); // todas
/* Ejemplo de $details['groups']:
[
	'type' => 'manyToMany',
	'singleton' => false,
	'pivots' => [ ['groups_users','group_id','groups_users','user_id'], ... ],
	'model' => App\Models\GroupModel::class,
]
*/

// Solo una relación concreta
$groupMeta = $model->relationDetails('groups');

$user = $userModel->find(1); // todavía sin 'groups'
$user->load(['groups','permissions']); // fuerza carga
echo count($user->groups);

public bool $collectMetrics = false;        // métricas de carga
public bool $cacheRelationResults = false;  // cache en memoria por request de resultados reindexados
public string $belongsToStrategy = 'join';  // reservado para futura estrategia 'in'

$config = config('Relations');
$config->cacheRelationResults = true;
$users = $userModel->with('groups')->findAll();
// segunda llamada reutiliza resultados en memoria (sin nueva query)
$again  = $userModel->with('groups')->findAll();

\App\Models\UserModel::clearRelationResultCache();

class ServicerModel extends Model implements RelatableInterface {
	use \Daycry\Relations\Traits\ModelTrait;

	protected $table = 'servicers';
	protected $primaryKey = 'id';

	// Promote the default hasMany (servicers -> lawyers) to a hasOne
	protected array $relationTypeOverrides = [
		'lawyers' => 'hasOne',
	];
}

$servicer = (new ServicerModel())->with('lawyers')->find(1);
// Access singular promoted relation
echo $servicer->lawyer->name;
// Property 'lawyers' will not be set since the relation is treated as singleton.

// User hasMany Widgets
$user = $userModel->with('widgets')->find($userId);
echo "User {$user->name} has " . count($user->widgets) . " widgets.";

// ... but a Widget belongsTo one User
$widget = $widgetModel->with('users')->find($widgetId);
echo $widget->name . " belongs to " . $widget->user->name;

/* Define your models */
class UserModel
{
	use \Daycry\Relations\Traits\ModelTrait;

	protected $table = 'users';
	protected $with  = 'widgets';
...
	
/* Then in your controller */
$groups = $groupModel->whereIn('id', $groupIds)->with('users')->findAll();

foreach ($groups as $group)
{
	echo "<h1>{$group->name}</h1>";
	
	foreach ($group->users as $user)
	{
		echo "{$user->name} is a {$user->role} with " . count($user->widgets) . " widgets.";
	}
}
bash
php spark relations:inspect model=App\\Models\\UserModel
php spark relations:inspect model=App\\Models\\UserModel --details
php spark relations:inspect model=App\\Models\\UserModel --details --only=groups,permissions
php spark relations:inspect model=App\\Models\\UserModel --details --json > relations.json
shell
php spark schemas