spotorm / spot2

Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer
http://phpdatamapper.com
BSD 3-Clause "New" or "Revised" License
601 stars 101 forks source link

Struggling with belongsTo relationship #261

Closed diego-sorribas closed 6 years ago

diego-sorribas commented 6 years ago

I have this issue and I can not found the error, maybe someone can help me. I have a Entity called Programs with this relationship 'pais' => $mapper->belongsTo($entity, Country::class, 'pais'),

Then I fetch one program with this line $program = $this->spot->mapper(Program::class)->all()->where(['id' => $programId])->with(['pais'])->first();

It triggers this two queries SELECT * FROMprogramasWHEREprogramas.id= '4' LIMIT 1 SELECT * FROMpaisesWHEREpaises.idIN ('32')

But when I print $program->pais it return 32 not the object of the relationship, is that okay???

Thanks

vlucas commented 6 years ago

All the relations are un-executed query objects that return collections. You can't really print them, but you can loop over them, count them, and execute them.

What happens when you loop over it or count it?

i.e count($program->pais) or foreach($program->pais as $pai) { echo $pai; }

diego-sorribas commented 6 years ago

Is not a collection, it is a 1-N relationship, "pais" is country in english

vlucas commented 6 years ago

You are still working with a Relation object though. In this case, \Spot\Relation\BelongsTo. This is because Spot lazy-loads the results only when you need them rather than eager-loading the entity objects.

If you want to print the resulting entity, you can use ->entity() to get it.

i.e. $program->pais->entity() for the Entity object or $program->pais->someFieldName for a single field value.

Source: https://github.com/spotorm/spot2/blob/master/lib/Relation/BelongsTo.php#L81

FlipEverything commented 6 years ago

Feel free to reopen this thread if you need further assistance.