Save tags to articles (belongsToMany) with joinData

Thanks for your help. I finally came up with this solution (maybe not the only solution and maybe not the best). Maybe you (or sb. else) will have a look on it. In the beforeMarshal of the ArticleTable, I modify the requestData expected (as per the docs/book says). But I have to set the foreign_key to a dummy value, since the validator says it is required. This foreign_key-column will automatically be replaced with the correct id lateron. The user_id as grabbed from the articles entity.

ArticlesTable.php

public function beforeMarshal($event, $data, $options)
    {
        foreach ($data as $key => $value) {
            if($key == "tags" && is_array($value)) {
                foreach ($value as $idx => $tag_id) {
                    $tag = [
                        'id' => (int)$tag_id,
                        '_joinData' => [
                            'foreign_key' => -1,
                            'user_id' => $data['user_id'],
                            'section' => 'articles'
                        ]
                    ];
                    $tags[] = $tag;
                }
                $data['tags'] = $tags;
            }
        }
    }

Is that correct / a good approach / just a workaround? Thanks !

1 Like