nextras / orm

Orm with clean object design, smart relationship loading and powerful collections.
https://nextras.org/orm
MIT License
309 stars 59 forks source link

HasMany after persist doesn't show entities #338

Closed attreid closed 4 years ago

attreid commented 5 years ago

When Entity is persisted HasMany property does not contain entities (are pushed to variable tracked)

Is posible to add this to method getCollection in HasMany.php?

if ($this->toAdd || $this->tracked || $this->toRemove) {
    $all = [];
    foreach ($collection as $entity) {
        $all[spl_object_hash($entity)] = $entity;
    }
    foreach ($this->toAdd as $hash => $entity) {
        $all[$hash] = $entity;
    }
    foreach ($this->tracked as $hash => $entity) {
        $all[$hash] = $entity;
    }
    foreach ($this->toRemove as $hash => $entity) {
        unset($all[$hash], $this->tracked[$hash]);
    }

    $collection = new ArrayCollection(array_values($all), $this->getTargetRepository());
    $collection = $this->applyDefaultOrder($collection);
}
hrach commented 5 years ago

Could you please elaborate more specifically what is the problem? When entity is persisted, the getCollection() has actually a fresh data refresh here: https://github.com/nextras/orm/blob/f1aae3318765ded805bbc1b859cf4d8e0b5ea676/src/Relationships/HasMany.php#L279-L280

attreid commented 5 years ago

Ok I have simplified entity

/**
 * @property string $id {primary}
 * @property ManyHasMany|OtherEntity[] $others {m:m OtherEntity, isMain=true, oneSided=true}
 */
class MyEntity extends Entity {
}

When its created, its ok

$entity = new MyEntity();
$orm->myEntities->attach($entity);

$other = new OtherEntity();
// add some data

$entity->others->add($other);
 foreach( $entity->others as $other){
// no problem, its here
}

$this->orm->persist($entity);

 foreach( $entity->others as $other){
// its empty
}

And after flush is still empty

hrach commented 5 years ago

Is it the persist call running an sql query? Do you have correct mapping for relationship columns? There may be a bug, but I honestly hope that such basic behavior is well tested both with out tests and by Orm users. Will take a look later.

attreid commented 5 years ago

Persist call sql query correctly. This problem is only with new row in db. When row is exists and I call work with 'others' entity in foreach after persist, foreach correctly gets rows. And I forgot an important note. Its MsSql

hrach commented 4 years ago

Please, provide more info - e.g. a failing PR/zip with failing code. I cannot reproduce it. Will gladly reopen to fix it.