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
  • Structure
  • Migrating
  • Relationships when the foreign key is accessible
  • Relationships when you need complex logic to get a foreign key

Was this helpful?

  1. Getting started
  2. Migrating legacy agents
  3. Code transformations

Smart Relationships

PreviousSmart FieldsNextSmart Segments

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.

Smart relationships are very different between the two versions of the Agent.

You can find the full documentation of relationship customization .

Structure

Smart relationships on legacy agents were declared creating a smart field with a reference property but differed in the way that:

  • Relationships to a single record (many-to-one or one-to-one) worked using the get function which needed to return a single record.

  • Relationships to a list of records (one-to-many or many-to-many) worked by implementing all the CRUD routes on a router file.

The new system is completely different: it is based on primary keys and foreign keys.

Migrating

Relationships when the foreign key is accessible

// Model
class Product extends Model
{
    public function buyers(): SmartRelationship
    {
        return $this->smartRelationship(
            [
                'type' => ['String'],
                'reference' => 'customer.id'
            ]
        );
    }
    ...

// routes/web.php
Route::get('forest/product/{id}/relationships/buyers', [ProductsController::class, 'buyers']);

// Controller
class ProductsController extends ForestController
{
    public function buyers(int $id): JsonResponse
    {
        $query = Customer::whereHas('orders.products', fn ($query) => $query->where('products.id', $id))
            ->paginate($pageParams['size'] ?? null, '*', 'page', $pageParams['number'] ?? null);

        return response()->json(
            JsonApi::render($query, 'customers', ['count' => $query->total()])
        );
    }
}
// Create the relationship
$forestAgent->customizeCollection(
    'Product',
    function (CollectionCustomizer $builder) {
        $builder->addManyToOneRelation(name: 'buyers', foreignCollection: 'Customer', foreignKey: 'customerId');
    }
);

// Create the reverse relationship
$forestAgent->customizeCollection(
    'Customer',
    function (CollectionCustomizer $builder) {
        $builder->addOneToManyRelation(name: 'products', foreignCollection: 'Product', originKey: 'customerId');
    }
);

Relationships when you need complex logic to get a foreign key

In this example, we want to create a relationship between the order collection and the address collection (assuming that it does not already exist in the database because depends on complex logic).

We can see that in the legacy agent, the delivery_address field was a smart field that returned the full address of the order, while in the new agent, we will create a computed field that will contain the address ID (the foreign key), and then create the relationship.

We won't be detailing the migration of a relation to a list of records here, but it is very similar to the one described below.

This will be much faster and will not require In filter operators to be implemented (as unlike computed fields, imported fields are natively filterable and sortable).

class ProductsController extends ForestController
{
    public function buyers(int $id): JsonResponse
    {
        $query = // complex query

        return response()->json(
            JsonApi::render($query, 'customers', ['count' => $query->total()])
        );
    }
}
$forestAgent->customizeCollection(
    'Product',
    function (CollectionCustomizer $builder) {
        $builder->addField(
            'customerId',
            new ComputedDefinition(
                columnType: 'Number',
                dependencies: ['id'],
                values: function ($customers, $context) {
                    ...
                }
            )
        )
        ->replaceFieldOperator(
            'customerId',
            'In',
            function ($customerIds, $context) {
                ...
            }
        )
        ->addManyToOneRelation(name: 'buyers', foreignCollection: 'Customer', foreignKey: 'customerId');
    }
);

If the foreign key was already present in the database in a related table, use the feature to move it to the correct collection instead of using a computed field.

here
import-rename-delete