Attach to a belongsToMany Relation

I got the following relation on my Object model:

    public $belongsToMany = [
        'tags' => [
            Tag::class,
            'table' => 'rel_objects_tags',
            'conditions' => 'type = 0',
            'order' => 'name',
        ],

and this method on my object model:

public function tags()
    {
        // return $this->belongsToMany(Tag::class, "rel_objects_tags");
        return $this->belongsToMany(
            $this->belongsToMany['tags'][0],
            $this->belongsToMany['tags']['table']
        );
    }

To make this code work:

$object->tags()->attach([1, 2, 3]);
$object->tags()->detach([4, 5, 6]);

But now I wonder:
There’s no better way to implement the tags() method then rewriting the information from the relation!? I couldnt find any info that helped here, but I would expect something like “relationMethod: true” as property in the belongsToMany array so this is implemented automatically or so.

Even the fact that I have to pass the relation parameters again…

This definitly seems like I have overlooked something which makes this process easier, but I cannot find it.

Thx for any help here. :slight_smile:

why would you rewrite the tags method? the cms is already handling it for you I believe.

so your code $object->tags()->attach([1, 2, 3]); is already working without rewriting the method.

1 Like

what if I tell you when I did so, it always told me attach() was unknown!? o_O

Hm… maybe I used the property instead of the method, no idea…

Lots of work for nothing. At least now I know. Thx ^^