laravel-dynamodb icon indicating copy to clipboard operation
laravel-dynamodb copied to clipboard

Filter model related records when using scan()

Open kitar opened this issue 3 years ago • 2 comments

DynamoDB, by its nature, often stores multiple models in a single table.

This is not a problem when writing a query to narrow down like this,

App\Models\User::filter('sort', '=', 'profile')->scan();

but because we are scanning the model, it is more natural to just scan it.

App\Models\User::scan();

Global Scopes seems useful in this case, but since Scope is a feature of Eloquent Builder and we don't extend it (we extend Database Query Builder), we can't use Laravel's scope feature as it is.

kitar avatar Jan 25 '22 16:01 kitar

Ideas

I'm wondering if we couldn't use the with semantic of eloquent, and then maybe even have an additional Model to extend from which is geared a bit more specific towards singletable pattern and make the sortKey opinionated.

Those two models could now have a few, opinionated, functions like:

  • a *Primary Model controls the PK, this also benefits the normal SingleTableModel as it could relate to the Primary and automatically assume a PK
  • sortKeyPart could be used to build the full SK automatically
  • sortKeyPart could also just be assumed from the Class Name
  • maybe even assume the PK for secondary models with a eloquentish "belongsTo" way

User

class User extends SingleTableModelPrimary
{
    protected $table = 'UsersAndProducts';
    protected $primaryKey = 'id';
    protected $sortKeyPart = 'User#';
}

Order

class Order extends SingleTableModel
{
    protected $table = 'UsersAndProducts';
    protected $primaryKey = 'user_id';
    protected $sortKeyPart = 'Order';
}

OrderItem

class OrderItem extends SingleTableModel
{
    protected $table = 'UsersAndProducts';
    protected $primaryKey = 'user_id';
    protected $sortKeyPart = 'OrderItem';
}
PK SK Name Total email amount
1 User# John Doe [email protected]
1 Order#1 50
1 Order#1#OrderItem#1 Red ball 50

marvinosswald avatar Jun 05 '22 08:06 marvinosswald

@marvinosswald Thanks for the idea! This is interesting.

Could you share more details of SingleTableModel and usage of the given models?

At this time, I’m overriding the find() method to automatically build the entire key. For example: https://github.com/kitar/simplechat/blob/56fe0b3840dd7c94087eed694215bd23819898be/app/Models/User.php#L45-L57

It just works, but it could be better if we could do this in a more generic way (like sortKeyPart).

kitar avatar Jun 06 '22 06:06 kitar