We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Query forced before every single update?

Hello

This is my first intervention in this forum, I'm trying to create my first project on phalcon. I just can't update a relation after the first saving, at least if I don't query the same object again.

My relationships...

For Bands class.
$this->hasMany('id', '\App\Models\Songs', 'band_id', ['alias' => 'Songs']);
For Songs class.
$this->belongsTo('band_id', '\App\Models\Bands', 'id', [
    'alias' => 'Band'
]);

This doesn't works for me

$band1 = new Bands();
$band1->name = 'Band 1';
$band1->save();

$song1 = new Songs();
$song1->band = $band1;
$song1->name = 'Song 1';
$song1->save();

$band2 = new Bands();
$band2->name = 'Band 2';
$band2->save();

$song1->band = $band2;
$song1->update();

I get this error message...

'Record cannot be updated because it does not exist'

The same if I try this way...

$song1 = Songs::find(['id' => $song1->id]);
$song1->band = $band2;
$song1->update();

The only way that I can make it work is this...

$song1 = Songs::find(['id' => $song1->id]);
$song1->band = $band2;
$song1->save();

So, my questions are...

  1. Update is just for non-relationships properties?
  2. Is not possible to modify objects references to relationships once defined without querying again?
  3. How can I add double lines using markdown in this editor =) ?

I'm interested to see what answers you get. If memory serves me (and it might be failing), save()-ing doesn't update the ID of the Song object. Only loading it from the database will do that.

Hi

I tried it 3 different ways, the first using update.

But it seems like the update method can't deal with foreign keys.

Have you tried not using update()? Just use save() and Phalcon will determine whether it neesd to create a new row or update an existing row.

I tried multiple ways, but the only way it can update external references is by refreshing the object by using a new query.