php - saving hasMany always add record instead of updating -
i have hasmany
relationship (let's post
hasmany comments
)
i want edit both post
, existing comment
@ same time
my code
in comment edit.ctp
file did
<?= $this->form->create($post); ?> <?= $this->form->input('title'); ?> <?= $this->form->input('title'); ?> <?= $this->form->input('text'); ?> <?= $this->form->input('comments.0.id'); ?> <?= $this->form->input('comments.0.text'); ?>
and in postscontroller
$post= $this->posts->get($id); $post= $this->posts->patchentity($post, $this->request->data, ['associated' => ['comments']]);
my problem
now expect comment updated, instead cake adds new comment every time.
what did do
i tried debug $this->request->data
, got
[ 'text' => 'this test', 'comments' => [ (int) 0 => [ 'id' => '168', 'text' => 'comment test', ] ] ]
but if debug $post
get
object(app\model\entity\post) { /* ... */ 'comments' => [ (int) 0 => object(app\model\entity\comment) { 'text' => 'comment test', '[new]' => true, '[accessible]' => [ '*' => true ], '[dirty]' => [ 'text' => true ], /* ... */ } ], /* ... */ '[dirty]' => [ 'comments' => true, ], }
so why comment marked 'new' when pass id
controller?
of course on simplified version of actual situation. maybe problem it's not in above code , have elsewhere in other code.
my question here if i'm doing basic approach error.
you need read associated data entity in order able patch it, otherwise data won't merged, marshalled, , ends being handled "new".
automatically loading associated data happens special _ids
key, , when there @ least 1 entry in association property, ie don't need have associated data loaded want patch, there must something in order marshaller reach point data being read , merged.
to exact, without data in comments
property, marshaller step out here
https://github.com/cakephp/cakephp/blob/3.2.8/src/orm/marshaller.php#l653-l655
i can't tell whether there might bug, @ least guess docs need updated around this, little misleading. while try explain happens when associated data missing in source entity, shown example doesn't work, , new entities created belongsto
, hasone
associations, incorrect.
cookbook > database access & orm > saving data > patching hasmany , belongstomany
you may want file issue on @ github clarification.
tl;dr
long story short, contain comments , should good.
$post = $this->posts->get($id, [ 'contain' => ['comments'] ]); // ...
Comments
Post a Comment