2
<?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->loja = $loja) 然后保存?

4

1 回答 1

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

于 2010-12-14T08:22:18.690 回答