假设我有2个型号:
class Model_Student extends ORM
{
protected $_table_columns = array(
'student_id' => array(),
'first_name' => array(),
'last_name' => array()
);
protected $_has_one = array(
'phone' => array()
)
}
和
class Model_Phone extends ORM
{
protected $_table_columns = array(
'student_id' => array(),
'number' => array(),
);
protected $_belongs_to = array(
'student' => array()
)
}
如何创建新的手机对象并将其添加给用户?
这是正确的方法吗?
$student = ORM::factory('student', 1); // Load student with id=1
$phone = ORM::factory('phone');
$phone->student_id = $student->student_id;
$phone->number = '1234567890';
$phone->save();
在这种情况下,我手动建立了连接:
$phone->student_id = $student->student_id;
ORM可以自动建立此连接吗?如果是,怎么样?
我想做这样的事情:
$student = ORM::factory('student', 1); // Load student with id=1
$phone = ORM::factory('phone');
$phone->number = '1234567890';
$student->add('phone', $phone);
但 add (对我来说很多)很多连接。 那么如何保存手机型号并将其附加到用户?
答案 0 :(得分:2)
如果你想使用与'id'不同的PK(students.student_id),请确保你的模特知道它:
class Model_Student extends ORM
{
protected $_primary_key = 'student_id';
protected $_table_columns = array(
'student_id' => array(),
'first_name' => array(),
'last_name' => array()
);
protected $_has_one = array(
'phone' => array()
)
}
你也可以省略$ _table_columns - 让Kohana自己发现它们。
关于关系:你可以做这件事:
$student = ORM::factory('student', 1); // Load student with id=1
$phone = ORM::factory('phone');
$phone->student = $student;
$phone->number = '1234567890';
$phone->save();
// ------------
$phone = ORM::factory('phone', 1);
echo $phone->student->first_name;
// ------------
$student = ORM::factory('student', 1);
echo $student->phone->number;
答案 1 :(得分:1)
AFAIK没有这种一对一关系的方法。所以你这是正确的方法:
$student = ORM::factory('student', 1); // Load student with id=1
$phone = ORM::factory('phone');
$phone->student_id = $student->student_id;
$phone->number = '1234567890';
$phone->save();
但在你的情况下,不要将手机存放在单独的表中,因为它只会使事情变得更复杂。只需将电话列添加到用户表即可。