Many-to-many relation in afterSave hook


#1

im having trouble implementing many-to-many relation in afterSave hook…
looking for an example…
PS: the example in the documentation isn’t working.
model : Tree.php

$this->addField('branches', ['never_persist' => true]);
$this->addHook('afterSave',function ($m)
    {
        $m->ref('TreeBranch')->import($m['branches']);
    }
);

TreeBranch model holds the many-to-many relation via tree_id, branch_id records


#2

Please be more specific what means “isn’t working”. Do you get some exception or isn’t data stored or what?
Also please show more of your code. Do you have line $this->hasMany(‘TreeBranch’);? What data and how you set in ‘branches’ field.
Basically I would need small test case and then can tell you what’s wrong or fix in Agile Data (or in documentation) if needed.


#3

I was unable to implement the documentation example in my case (with never_persist = true).
The solution was to add a json column branches_ref in the tree table…

documentation example
my example


#4

I am working on a pull request, for now will add some test-cases, but the idea is to significantly improve and document our ability to lookup things using field in foreign model.

Although not covered by this PR, but as a suggested follow-up I have included that we will need ability to lookup and populate many-to-many relationship when our ingest data has arrays matching to hasMany lookup fields.