Hello again! I have two models: List, which has ID as primary key, and ListItem which has NO id, but primary key is composed of two columns: (list_id, user_id). I know laravel does not allow to use composite keys on eloquent models, but I really don't want to add autoincremental 'id' for this table. So I use third-party package 'coenjacobs/eloquent-composite-primary-keys'. It works very well for my last 2 projects and I wanted to use it in my current API project.
Is it possible to use somehow composite key as resource key?
Yes this should be possible. You'll need to use a JSON API resource key that joins the list_id and user_id together, e.g. list_id-user_id. Then you'd need to overload the find and exists methods on your Adapter:
public function find($resourceId)
{
$ids = explode('-', $resourceId);
if (2 !== count($ids)) {
return null;
}
return ListItem::find(['list_id' => $ids[0], 'user_id' => $ids[1]]);
}
public function exists($resourceId)
{
$ids = explode('-', $resourceId);
if (2 !== count($ids)) {
return false;
}
return ListItem::where(['list_id' => $ids[0], 'user_id' => $ids[1]])->exists();
}
That should get you started. For relationships, you'll probably need to extend one of the relationship objects in our Eloquent namespace to do the same exploding of the id before writing a relationship.
In your Schema getId() method you'd have to do:
public function getId($resource)
{
return "{$resource->list_id}-{$resource->user_id}"
}
Awesome! Thank you!
Most helpful comment
Yes this should be possible. You'll need to use a JSON API resource key that joins the
list_idanduser_idtogether, e.g.list_id-user_id. Then you'd need to overload thefindandexistsmethods on your Adapter:That should get you started. For relationships, you'll probably need to extend one of the relationship objects in our
Eloquentnamespace to do the same exploding of the id before writing a relationship.