1

I have the following table in my mysql DB

mysql

I have a model Shipment and i am using Phalcon's ORM to interact with my DB. The master_id field in this table is actually the id of another raw, but in the same table, as you can see in the picture. The id=1 is the Master Shipment and id=2 and id=3 are Subshipments.

My model right now looks like this

class Shipment extends Model
{
    protected $id;
    protected $hawb;
    protected $master_id;

    public function initialize()
    {
        parent::initialize();

        $this->hasMany(
            'id',
            'Shipment',
            'master_id'
        );
    }
    //setters and getters are here
}

When I am using $shipment = ShipmentModel::findFirst($id); in my Controller, i can see the master_id of the Shipment.

What i want to have is, call another function from my Shipment model in order to retrieve all the SubShipments as a Collection of Shipment models, or at least an array with Shipment models.

Or even better, if the ShipmentModel::findFirst($id); could populate the SubShipments automatically (if there are any) would be the best!

I don't really know if the $this->hasMany that I have is correct over there, so if someone could show me how to proceed I would be grateful :)

GeorgeGeorgitsis
  • 1,262
  • 13
  • 29
  • 2
    There is a similar question here https://stackoverflow.com/questions/45534869/phalcon-implement-one-to-many-self-referencing-relationship-in-model/45535716#45535716 Please, take a look and let me know :) – Nikolay Mihaylov Jun 01 '18 at 09:40
  • `Model 'Shipment' could not be loaded Phalcon\Mvc\Model\Manager->load('Shipment') Phalcon\Mvc\Model\Manager->getRelationRecords(Object(Phalcon\Mvc\Model\Relation), NULL, Object(Project\API\Models\Customer\Shipment), NULL) #2 /var/www/project/app/src/Controllers/Shipment.php(55): Phalcon\Mvc\Model->getRelated('subShipments') #3 [internal function]: Project\API\Controllers\Shipment->getShipment('2LzXEvabvaOwWVq') #4 [internal function]: Phalcon\Mvc\Micro\LazyLoader->__call('getShipment', Array) #5 [internal function]: Phalcon\Mvc\Micro\LazyLoader->callMethod('getShipment', Array, NULL)` – GeorgeGeorgitsis Jun 01 '18 at 09:51
  • I have a server error `Model 'Shipment' could not be loaded`. Above i pasted the exception i have in my logs. Don't know why it cannot load the model :/ – GeorgeGeorgitsis Jun 01 '18 at 09:52

1 Answers1

3

You need to provide full namespace, not just class name - to solve this Model 'Shipment' could not be loaded. Best is to add alias:

$this->hasMany(
    'id',
    Shipment::class,
    'master_id',
    ['alias' => 'subShipments'])
);

And then just use:

Shipment::findFirst()->getSubShipments() you can add such method if you want and do return $this->getRelated('subShipments')

Juri
  • 1,369
  • 10
  • 16