假设我有 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(据我所知)适用于多对多连接。 那么如何保存手机型号并将其附加给用户呢?
最佳答案
如果您想使用与“id”(students.student_id) 不同的 PK,请确保您的模型知道它:
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;
关于php - 如何在Kohana ORM中处理belongs_to关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8645545/