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

Lookup Table Model Relation

Hello,

I have a wierd problem - when updating a model's property that references a lookup table - the lookup table's row is changing.

I have an Orders Model that has a status_id property that references OrdersStatuses table. This allows me to get a workflow structure.

$this->hasOne( "status_id", "Models\Orders\OrdersStatuses", "id", ['alias'=>'status'] );

I also tried with 'belongsTo'

OrdersStatuses has an id, name and next_status, an id that references which OrdersStatuses is next.

$next_status = OrdersStatuses::findFirst($order->status->nex\t_status);

$order->status_id = $next_status->id;

This changes the OrdersStatuses table's data:

Ex with the following: orders_statuses

id | name | next_status

1 | Paid | 2

2 | Ready | 3

3 | Delivered| 4

orders

id | status_id

1 | 1

this would change orders.status\id to 2, BUT it will also change orders_status:

id | name | next_status

1 | Ready | 2

2 | Ready | 2

3 | Delivered| 4

Its changing the destination row's name to the previous name, and the next_status. What am i doing wrong?

Thanks

$this->belongsTo( "status_id", "Models\Orders\OrdersStatuses", "id", ['alias'=>'status'] );

It should be belongSto. Best just just not use magic property. Add method getStatus() :

public function getStatus()
{
    return $this->getRelated('status');
}


1.3k
$this->belongsTo( "status_id", "Models\Orders\OrdersStatuses", "id", ['alias'=>'status'] );

I mentioned that ive tried the belongsTo relation, but that doesnt update status_id on the orders table. However, its not changing the status row like hasOne - so half way there.

Do i have to setup the reverse relation, ie. OrdersStatuses hasMany orders?

Did you added getter and tried using it?



1.3k

Did you added getter and tried using it?

Yes, i added the getter in the model and modified the code:

$this->belongsTo( "status_id", "Models\Orders\OrdersStatuses", "id", ['alias'=>'status'] );

And in the controller

$current_status = $order->getStatus();

$next_status = OrdersStatuses::findFirst($current_status->next_status);

$order->status= $next_status;

this also doesnt work

$order->status_id = $next_status->id;

If i use belongsTo, the status_id column is not changed. If i use the hasOne, the status id is changed along with the lookup row. Is this a bug?