staudenmeir / eloquent-json-relations

Laravel Eloquent relationships with JSON keys
MIT License
982 stars 63 forks source link

Be able to define Relationships with multiple keys instead of just one #82

Closed didac-adria closed 5 months ago

didac-adria commented 2 years ago

Hey!

Lovely package, thanks for sharing.

I've just found out a case which could be interesting for other people. Currently, in Laravel relationships, you can pass an array of keys when defining the relationship to another table. Instead of looking for the id only in the related table, it will look for all the values specified in the array of keys of the relationship. Nevertheless, the current implementation of this package doesn't allow us to pass an array of keys to query for. For example, the BelongsToJson relationship allows only strings as foreighKey and ownerKey.

Implementation for this package: image

Implementation for the Laravel standard relationships: image

In my case, I'm trying to define a relationship to a table which contains repeated id records. So, to find the correct ones, I need to look for the id but also team_id to get the correct resources. I can't define the relationship only with the id with the other table.

That could be a nice feature!

staudenmeir commented 2 years ago

Hi @didac-adria, What do the migrations of both your tables look like? Please also share some sample data.

Supporting multiple keys is quite complex, that's also why https://github.com/topclaudy/compoships only works with the simplest Laravel relations.

didac-adria commented 2 years ago

Oh I forgot to mention compoships! Yes, I know that only works with simplest relationships. But I thought that, in reality this is a "simple" relationship where the only difference is that we save multiple id keys in an array. So that could be possible. But I say that without haven't dug too much into how this could be done, so I could be wrong.

Regarding migrations, we don't save migrations. We squash migrations. But I can share the columns schema.

This is the table where we want to put the relationship. The "rentals" column is the one containing the json with the id's to the rentals this settlement refers to:

image

And this is the schema of the rentals table. I just cut some columns wich are irrelevant for this topic. As there might be multiple id's in this table, to find a rental in this table, we query by id and team_id:

image image
staudenmeir commented 6 months ago

I've released a new version (Laravel 10+) with support for composite keys: https://github.com/staudenmeir/eloquent-json-relations?tab=readme-ov-file#composite-keys

class Settlement extends Model
{
    public function jsonRentals()
    {
        return $this->belongsToJson(
            Rental::class,
            ['rentals', 'team_id'],
            ['id', 'team_id']
        );
    }
}
didac-adria commented 6 months ago

Great news thank you!