kitar / laravel-dynamodb

A DynamoDB based Eloquent model and Query builder for Laravel.
MIT License
179 stars 27 forks source link

Filter model related records when using scan() #14

Closed kitar closed 1 year ago

kitar commented 2 years ago

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.

marvinosswald commented 2 years ago

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:

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 john@doe.me
1 Order#1 50
1 Order#1#OrderItem#1 Red ball 50
kitar commented 2 years ago

@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).