What is the optimal way to update an entity that has a hasManyThrough
relationship?
Let’s say you have a Post
entity that has the following relationship definition:
// Post Entity
/**
* This has many Categories through PostCategories
*/
function categories() {
return hasManyThrough( [ "PostCategories", "Category" ] );
}
/**
* This has many PostCategories
* note: this relationship entity contains extra data (like `rowOrder` sorting)
*/
function postCategories() {
return hasMany( "PostCategory" );
}
The user wants to update a Post
and the rc
contains a list of categoryId
values like this:
// rc scope
{
"id": "1", // post id
"categoryId": "2,3,4"
}
If I execute the following code in my handler, I get an exception, “Method does not exist on QueryBuilder [applySetter]”
prc.categories = getInstance( "Category" ).whereIn( "id", rc.categoryId ).get();
prc.post.setCategories( prc.categories );
I also tried saveMany()
, but I got “Method does not exist on QueryBuilder [saveMany]”
prc.categories = getInstance( "Category" ).whereIn( "id", rc.categoryId ).get();
prc.post.categories().saveMany( prc.categories );
This leads me to believe that you can not persist relational data via the hasManyThrough
relationship.
The only alternative I can think of is to manually loop through the rc.categoryId
list, look for an existing PostCategory
entity, and either create or update it. Additionally, I would then need to look for any PostCategory
entities that aren’t in the list of rc.categoryId
and delete them.
This workaround feels like a lot of manual work that an ORM should take care of automatically. Surely I must be tackling this problem all wrong. Is there a better and more “Quick” way to handle updating relationships like this?
Note: I don’t want to overwrite all PostCategory
entities with every save, because there are columns in the post_category
table, like rowOrder
that needs to be preserved.