我与1:n
和Client
之间存在Addresses
关系。客户端可以有多个地址。
我创建了以下模型:
class Client extends ModelBase
{
$this->hasMany("id", "ClientAddress", "client_id", array(
"alias" => "addresses"
));
class ClientAddress extends ModelBase
{
public function initialize()
{
parent::initialize();
$this->belongsTo("client_id", "Client", "id", array(
"alias" => "client"
));
$this->belongsTo("address_id", "Address", "id", array(
"alias" => "address"
));
}
class Address extends ModelBase
{
我想在Address
上执行一些CRUD操作。
我尝试创建新的Address
并使用以下内容链接到ClientAddress
。它确实在Address
表中创建了记录,但它没有通过ClientAddress
表链接到它。
$client = Client::findFirst($current_client_id);
$address = new Address();
$address->setName( $this->request->getPost("name") );
$address->setAddress1( $this->request->getPost("address1") );
$address->setAddress2( $this->request->getPost("address2") );
$address->setSuburb( $this->request->getPost("suburb") );
$address->setState( $this->request->getPost("state") );
$address->setPostcode( $this->request->getPost("postcode") );
$address->setCountry( $this->request->getPost("country") );
$client->addresses = $address;
$client->save();
我在这里做错了什么?
答案 0 :(得分:1)
许多关系是一系列关系。一个微妙的变化,一切都应该有效。
$client->addresses[] = $address;
$client->save();
边栏:
我认为本杰明提出了关于地址关联的有效观点。想想亚马逊这样的网站,您可以从地址列表中选择要发送到的网站。它们与您的帐户相关联,而不是之前的订单。
我之前已经建立了几个电子商务和CRM关系,因此非常习惯这种模式。
答案 1 :(得分:0)
首先,对于1:n关系,您不需要交叉表。
尝试这样的事情
class Client extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasMany('id', 'Address', 'client_id', NULL);
}
}
class Address extends \Phalcon\Mvc\Model{
public function initialize()
{
$this->belongsTo('client_id', 'Client', 'id', array('foreignKey' => true));
}
}
编辑:
class Client extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasMany("id", "ClientAddress", "client_id");
}
}
class Address extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasMany("id", "ClientAddress", "address_id");
}
}
class ClientAddress extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->belongsTo("client_id", "Client", "id");
$this->belongsTo("address_id", "Address", "id");
}
}
可以通过这种方式进行通话
$client = Client::findFirst($current_client_id);
$address = new Address();
...
$address->save();
$clientAddress = new ClientAddress ();
$clientAddress->setClient_id($client->getId());
$clientAddress->setAddress_id($cddress_id->getId());
$clientAddress->save();
当出现问题时,可能会添加一些检查和回滚。