我刚刚开始研究使用Phalcon框架。我以前从未真正使用过框架(或者真正的MVC),所以这是一个学习曲线。
我创建了 2 个表:User
和 Client
.
一个客户端可以有多个User
,但一个用户只能有 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 = "lock@lock.com";
$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。