使用Phalcon和关系插入数据

问题描述:

我刚开始使用Phalcon框架。我从来没有真正使用过一个框架(或者真的是MVC),所以这是一个学习曲线。使用Phalcon和关系插入数据

我已经创建了2个表格:UserClient

客户端可以有很多User's,但用户只能有1 Client

我有以下型号:

<?php 
class User extends \Phalcon\Mvc\Model 
{ 
    public $id; 
    public $name; 
    public $email; 
    public $username; 
    public $password; 
    public $active; 
    public $isAdmin; 
    public $client; 

    public function initialize() 
    { 
    $this->setConnectionService('gateway-db'); 
    $this->belongsTo("clientId", "Client", "id"); 
    } 
} 

<?php 
class Client extends \Phalcon\Mvc\Model 
{ 
    public $id; 
    public $code; 
    public $name; 
    public $active; 

    public function initialize() 
    { 
    $this->setConnectionService('gateway-db'); 
    $this->hasMany("id", "User", "clientId"); 
    } 
} 

我想创建一个链接到现有Client用下面的代码的新User,但是ClientID的领域是NULL,而不是链接。

$client = Client::findFirstByCode("DEM"); 

$user = new User(); 
$user->email = "[email protected]"; 
$user->is_admin = 1; 
$user->username = "lock"; 
$user->active = 1; 
$user->name = "Lachlan"; 
$user->password = $this->security->hash("password"); 
$user->client = $client; 

我能做什么错?

字段clintId不存在。您需要使用$this->belongsTo("id", "Client", "id");。客户端模型也一样。

注意:您的字段client可能是一个整数,因此它不能包含整个$client对象。

尝试分配ID:$user->client = $client->id

也想想使用受保护的变量和getter/setter。