PHP Developer Guide
Other documentationsDemoCommunityGitHub
  • Forest Admin
  • Getting started
    • How it works
    • Quick start
      • Symfony
      • Laravel
    • Create your agent
    • Troubleshooting
    • Migrating legacy agents
      • Pre-requisites
      • Recommendations
      • Migration steps
      • Code transformations
        • API Charts
        • Live Queries
        • Smart Charts
        • Route overrides
        • Smart Actions
        • Smart Fields
        • Smart Relationships
        • Smart Segments
  • Data Sources
    • Getting Started
      • Collection selection
      • Naming conflicts
      • Query interface and Native Queries
        • Fields and projections
        • Filters
        • Aggregations
    • Provided data sources
      • Doctrine
      • Eloquent
        • Polymorphic relationships
    • Write your own
      • Translation strategy
        • Structure declaration
        • Capabilities declaration
        • Read implementation
        • Write implementation
        • Intra-data source Relationships
      • Contribute
  • Agent customization
    • Getting Started
    • Actions
      • Scope and context
      • Result builder
      • Static Forms
      • Dynamic Forms
      • Related data invalidation
    • Charts
      • Value
      • Objective
      • Percentage
      • Distribution
      • Leaderboard
      • Time-based
    • Fields
      • Add fields
      • Move, rename and remove fields
      • Override binary field mode
      • Override writing behavior
      • Override filtering behavior
      • Override sorting behavior
      • Validation
    • Hooks
      • Collection hook
      • Collection override
    • Pagination
    • Plugins
      • Write your own
    • Relationships
      • To a single record
      • To multiple records
      • Computed foreign keys
      • Under the hood
    • Search
    • Segments
  • Frontend customization
    • Smart Charts
      • Create a table chart
      • Create a bar chart
      • Create a cohort chart
      • Create a density map
    • Smart Views
      • Create a Map view
      • Create a Calendar view
      • Create a Shipping view
      • Create a Gallery view
      • Create a custom tinder-like validation view
      • Create a custom moderation view
  • Deploying to production
    • Environments
      • Deploy on AWS
      • Deploy on Heroku
      • Deploy on GCP
      • Deploy on Ubuntu
    • Development workflow
    • Using branches
    • Deploying your changes
    • Forest Admin CLI commands
      • init
      • login
      • branch
      • switch
      • set-origin
      • push
      • environments:create
      • environments:reset
      • deploy
  • Upgrade
    • Laravel agent upgrade to v3
  • Under the hood
    • .forestadmin-schema.json
    • Data Model
      • Typing
      • Relationships
    • Security & Privacy
Powered by GitBook
On this page
  • Displaying a link to the last message sent by a customer
  • Connecting collections without having a shared identifier

Was this helpful?

  1. Agent customization
  2. Relationships

Computed foreign keys

PreviousTo multiple recordsNextUnder the hood

Last updated 1 year ago

Was this helpful?

This is the official documentation of the forestadmin/laravel-forestadmin v2+ and forestadmin/symfony-forestadmin PHP agents.

You may want to create a relationship between 2 Collections, but you don't have a foreign key that is ready to use to connect them.

To solve that use case, you should use both and relationships.

This is done with the following steps:

  • create a new Field containing a foreign key,

  • make the Field filterable for the In operator (see as to why this is required),

  • create a relation using it.

Displaying a link to the last message sent by a customer

We have 2 Collections: Customers and Messages, linked together by a one-to-many relationship.

We want to create a ManyToOne relationship with the last message sent by a given customer.

use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceCustomizer\Decorators\Computed\ComputedDefinition;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Aggregation;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Filters\Filter;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Filters\PaginatedFilter;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\ConditionTreeFactory;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Projection\Projection;

$forestAgent->customizeCollection(
    'Customer',
    function (CollectionCustomizer $builder) {
        // Create foreign key
        $builder->addField(
            'lastMessageId',
            new ComputedDefinition(
                columnType: 'Number',
                dependencies: ['id'],
                values: function ($customers, $context) {
                	$customerIds = array_map(fn ($r) => $r['id'], $customers);

                    // We're using Forest Admin's query interface
                    $filter = new Filter(
                        conditionTree: ConditionTreeFactory::fromArray(
                            ['field' => 'customer_id', 'operator' => 'In', 'value' => $customerIds]
                        )
                    );
                    $aggregation = new Aggregation(operation: 'Max', field: 'id', groups: [[ 'field' =>'customer_id' ]]);
                    $rows = $context->getDatasource()->getCollection('Message')->aggregate($filter, $aggregation);

                    return array_map(
                        function ($customer) use ($rows) {
                            foreach ($rows as $row) {
                                if ($row['group']['customer_id'] === $customer['id']) {
                                    return $row['value'] ?? null;
                                }
                            }

                            return 0;
                        },
                        $customers
                    );
                }
            )
        )->replaceFieldOperator(
            'lastMessageId',
            'In',
            function ($lastMessageIds, $context) {
                $filter = new PaginatedFilter(
                        conditionTree: ConditionTreeFactory::fromArray(
                            ['field' => 'id', 'operator' => 'In', 'value' => $lastMessageIds]
                        )
                    );
                $records = $context->getDatasource()
                    ->getCollection('Message')
                    ->list($filter, new Projection(['customer_id']));

                return ['field' => 'id', 'operator' => 'In', 'value' => array_map(fn ($r) => $r['customer_id'], $records)];
            }
        )->addManyToOneRelation('lastMessage', 'Message', 'lastMessageId');
    }
);

Connecting collections without having a shared identifier

You have 2 Collections and both contain users: one comes from your database, and the other one is connected to the CRM that your company uses.

There is no common id between them that can be used to tell Forest Admin how to link them together, however, both Collections have firstName, lastName, and birthDate fields, which taken together, are unique enough.

use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceCustomizer\Decorators\Computed\ComputedDefinition;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Aggregation;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Filters\Filter;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Filters\PaginatedFilter;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\ConditionTreeFactory;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Projection\Projection;

/**
 * Concatenate firstname, lastname and birthData to make a unique identifier
 * and ensure that the new field is filterable
 */
$createFilterableIdentityField = function (CollectionCustomizer $collection) {
    // Create foreign key on the collection from the database
    $collection->addField(
        'userIdentifier',
        new ComputedDefinition(
            columnType: 'String',
            dependencies: ['firstName', 'lastName', 'birthDate'],
            values: fn($users) => array_map(fn($u) => $u['firstName'] .'/'. $u['lastName'] .'/'. $u['birthDate'] , $users),
        )
    );

  // Implement 'In' filtering operator (required)
  $collection->replaceFieldOperator(
      'userIdentifier',
      Operators::IN,
      fn ($values) => [
          'aggregator' => 'Or',
          'conditions' => array_map(
              fn ($value) => [
                  'aggregator' => 'And',
                  'conditions' => [
                      ['field' => 'firstName', 'operator' => Operators::EQUAL, explode('/', $value)[0]],
                      ['field' => 'lastName', 'operator' => Operators::EQUAL, explode('/', $value)[1]],
                      ['field' => 'birthDate', 'operator' => Operators::EQUAL, explode('/', $value)[2]],
                  ]
              ]
          ),
      ]
  );
};

/** Create relationship between databaseUsers and crmUsers */
$createRelationship = function (CollectionCustomizer $collection) {
    $collection->addOneToOneRelation(
        name: 'userFromCrm',
        foreignCollection: 'crmUsers',
        originKey: 'userIdentifier',
        originKeyTarget: 'userIdentifier',
    );
};

/** Create relationship between crmUsers and databaseUsers */
$createInverseRelationship = function (CollectionCustomizer $collection) {
    $collection->addManyToOneRelation(
        name: 'userFromDatabase',
        foreignCollection: 'databaseUsers',
        foreignKey: 'userIdentifier',
        foreignKeyTarget: 'userIdentifier',
    );
};

$forestAgent->customizeCollection('databaseUsers', $createFilterableIdentityField)
    ->customizeCollection('crmUsers', $createFilterableIdentityField)
    ->customizeCollection('databaseUsers', $createRelationship)
    ->customizeCollection('crmUsers', $createInverseRelationship);
computed fields
Under the hood