【问题标题】:Phalcon ORM field has relation with another field in same tablePhalcon ORM 字段与同一张表中的另一个字段有关系
【发布时间】:2018-11-11 09:38:42
【问题描述】:

我的 mysql 数据库中有下表

我有一个模型Shipment,我正在使用 Phalcon 的 ORM 与我的数据库进行交互。这个表中的master_id字段实际上是另一个raw的id,但是在同一个表中,如图所示。 id=1 是主货件,id=2 和 id=3 是子货件。

我现在的模型是这样的

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
}

当我在控制器中使用$shipment = ShipmentModel::findFirst($id); 时,我可以看到Shipmentmaster_id

我想要的是,从我的 Shipment 模型中调用另一个函数,以便检索所有 SubShipments 作为 Shipment 模型的集合,或者至少是带有 Shipment 模型的数组。

或者甚至更好,如果ShipmentModel::findFirst($id); 可以自动填充SubShipments(如果有的话)将是最好的!

我真的不知道我那里的$this->hasMany 是否正确,所以如果有人能告诉我如何继续,我将不胜感激:)

【问题讨论】:

  • 这里有一个类似的问题stackoverflow.com/questions/45534869/… 请看一下并告诉我:)
  • 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)
  • 我有一个服务器错误Model 'Shipment' could not be loaded。上面我粘贴了我的日志中的异常。不知道为什么它无法加载模型:/

标签: php mysql model phalcon phalcon-orm


【解决方案1】:

您需要提供完整的命名空间,而不仅仅是类名 - 解决这个问题Model 'Shipment' could not be loaded。最好是加别名:

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

然后只需使用:

Shipment::findFirst()->getSubShipments()你可以添加这样的方法,如果你想这样做return $this->getRelated('subShipments')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 2010-10-13
    • 2018-06-13
    • 2014-02-23
    • 1970-01-01
    • 2013-02-20
    相关资源
    最近更新 更多