开发者

Kohana 3 ORM: Saving relationships

开发者 https://www.devze.com 2023-01-30 02:52 出处:网络
<?php class Model_Cliente extends ORM { protected $_table_name = \'clientes\'; protected $_primary_key = \'id\';
<?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->ema开发者_如何学Pythonil = 'foobar@foobar.com';
$cliente->telefone = '123456789';
$cliente->novidades = true;
$cliente->loja = $loja;

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

I get the error: "Kohana_Exception [ 0 ]: The loja property does not exist in the Model_Cliente class".

Why cannot I add loja to cliente ($cliente->loja = $loja) and save then?


ORM model can set only belongs_to relations. So, you should reorder your code:

$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();

And dont forget to define $_belongs_to property in Model_Loja!

0

精彩评论

暂无评论...
验证码 换一张
取 消