Kohana 3 ORM:拯救人际关系

时间:2010-12-13 15:20:50

标签: kohana-3 kohana-orm database-relations

<?php
class Model_Cliente extends ORM {
protected $_table_name = 'clientes';
protected $_primary_key = 'id';
protected $_has_one = array('loja' => array());
}
?>

<?php
class Model_Loja extends ORM {
protected $_table_name = 'lojas';
protected $_primary_key = 'id';
}
?>

<?php
// code here ...
public function action_index()
{
$loja = ORM::Factory('loja');
$loja->nome = 'Foo Bar Store';
$loja->endereco = 'foobar';
$loja->senha = '123456';

$cliente = ORM::Factory('cliente');
$cliente->empresa = 'Foo Bar Ltda.';
$cliente->responsavel = 'João da Silva Foo Bar';
$cliente->email = 'foobar@foobar.com';
$cliente->telefone = '123456789';
$cliente->novidades = true;
$cliente->loja = $loja;

$cliente->save();
}
// code here ...
?>

我收到错误:“Kohana_Exception [0]:Model_Cliente类中不存在loja属性”。

为什么我不能将loja添加到cliente($ cliente-&gt; loja = $ loja)并保存呢?

1 个答案:

答案 0 :(得分:2)

ORM模型只能设置belongs_to关系。所以,你应该重新安排你的代码:

$cliente = ORM::Factory('cliente');
$cliente->empresa = 'Foo Bar Ltda.';
$cliente->responsavel = 'João da Silva Foo Bar';
$cliente->email = 'foobar@foobar.com';
$cliente->telefone = '123456789';
$cliente->novidades = true;
$cliente->save();  // save parent model before linking

$loja = ORM::Factory('loja');
$loja->nome = 'Foo Bar Store';
$loja->endereco = 'foobar';
$loja->senha = '123456';
$loja->cliente = $cliente; // the same as $loja->cliente_id = $client->id;

$loja->save();

不要忘记在$_belongs_to中定义Model_Loja属性!