How can I save a tag value in an entry in Craft 3 I am working on a plugin and I have the following code

private function _tagProducts(array $products, array $names)
{
    foreach ($products as $productId)
    {
        $product = Craft::$app-&gt;getElements()-&gt;getElementById($productId, Product::class, null);
        $product['businessTag'] = ['something'];
        $product['purchasedWithVoucher'] = 'no';
        Craft::$app-&gt;getElements()-&gt;saveElement($product);
    }
}


If I remove/comment out the line $product['businessTag'] = ['something']; this snippet runs just fine and updates the field purchasedWithVoucher just fine. But, if I keep the businessTag line in I get the following error.

(Integrity constraint violation – yii\db\IntegrityException)

I have tried updating the tag field as $product['businessTag'] = 'something'; which at least throws no errors, but the product is not updated with the new tag, however the $product['purchasedWithVoucher']; line does update so I know that simply saving the changes isn't the issue.
The trick here is that Tags are also elements, so you'll need to save them or look them up to assign them. Something like this:

    public function createOrGetTag($keyword, $groupId) {
        $tagQuery = new TagQuery(Tag::class);
        $tagQuery-&gt;groupId = $groupId;
        $tagQuery-&gt;title = $keyword;
        $tag = $tagQuery-&gt;one();

        if (!$tag) {
            $tag = new Tag();
            $tag-&gt;groupId = $groupId;
            $tag-&gt;title = $keyword;
            Craft::$app-&gt;elements-&gt;saveElement($tag);
        }

        return $tag;
    }


And then in your field setting, you'd do something like this:

$product-&gt;businessTag-&gt;id[] = $tag-&gt;id;