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

ORM Transaction Model relationships and saving

Hey guys,

I'm fairly confident the issue here is my lacking knowledge for how all this logically works together. I've read through the documentation a fair few times for models and I'm still not fully understanding what I'm missing in my code.

tl;dr: I have a model called 'Client' which has a 'hasMany' relationship with 'Clientcontactstype'. 'Clientcontactstype' has a 'belongsTo' relation back to 'Client' These models were generated using Phalon developer tools (Which I know can be buggy, but it seems to of gotten it right)

Here's the source for reference:

Clientcontactstype Model https://pastebin.com/sXKUzrjH

Client Model https://pastebin.com/NAg1caVj

Controller code https://pastebin.com/GctGiFWL

The problem code lies at line 11 on the Controller code:

Catchable fatal error: Object of class Client could not be converted to string

$clientContactType->client = $customer;

Am I right in saying that I shouldn't have to directly reference the $customer's ID, I should be able to use the model object itself? or am I missing something here.



3.2k
Accepted
answer
edited Jun '14

From what I see, client is already a database field of clientContactType so it can't be an alias for another table/model.

I would rename client to client_id so you can use $model->client freely

Or, if you don't want to do that, set an alias for the relation:

$this->belongsTo("client", "Client", "id", array("foreignKey"=>true, 'alias' => "clientmodel"));
edited Jun '14

I see your valid point and I'll take that on board for future practice, however renaming the field both in Phalcons reference and in the database table did not resolve the original issue :(

I also tried the alias approach, but no cigar.

The issue seems to be relating to the transaction because if I remove that, the controller is actioning as intended.

After a bit of playing around, and [email protected]'s help it turns out you were pretty much spot on.

There was a logic issue on the controller as well, because of the 1-n relationship between Client -> ClientContactsType, the controller should of been saving the Client, not the ClientContactsType which had a part in all this too.

Thanks for your help :)