cloudcreativity / laravel-json-api

JSON API (jsonapi.org) package for Laravel applications.
http://laravel-json-api.readthedocs.io/en/latest/
Apache License 2.0
780 stars 109 forks source link

Question: how/where to set connection for multi-tenant relationships #460

Closed genyded closed 4 years ago

genyded commented 4 years ago

Our app is multi-tenant and we have some related tables in a tenant specific database. We have middleware that toggle it when the route has a {record}, but when get include or related data for the parent collection, only the first one has the data.

When using Laravel API resources, we can set it on the parent resource in the toArray method. We tried it in you code in the Schema's get Relationship method, but it does not seem to have any impact:

public function getRelationships($conferences, $isPrimary, array $includeRelationships)
  {
     /*******  THIS IS OUR CODE ********/
    Config::set('database.connections.conf.database', $conferences->db);
    DB::reconnect('conf');
     /******  END OF OUR CODE *******/
    return [
      'categories' => [
        self::SHOW_SELF => true,
        self::SHOW_RELATED => true,
        self::SHOW_DATA => true, // isset($includeRelationships['categories']),
        self::DATA => function () use ($conferences) {
            return $conferences->categories;
        }
      ],
    ];
  }

We can dd and set it gets set, but the relationships are still going to the wrong DB. Where should we set something like this for your code?

TIA!

genyded commented 4 years ago

OK, figured this out. We moved the DB change into the relationship on the actual Model (where is probably should be). We just can't eager load in JSON API for the index methods and it all seems to work as expected. Closing this.

lindyhopchris commented 4 years ago

Great glad you got it sorted!