我可以通过参考保存新的相关对象而无需在Kohana 3的ORM中手动复制id吗?

时间:2010-09-29 21:47:24

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

我有2个物体。球员和比赛。玩家是Match的孩子。我想知道我是否可以同时创建这两个,而无需手动插入id。

$match = ORM::factory('match');

$player1 = ORM::factory('player');
$player2 = ORM::factory('player');

$player1->match = $match;
$player2->match = $match;

$match->save();
$player1->save();
$player2->save();

类似于Ruby中的ActiveRecord

1 个答案:

答案 0 :(得分:0)

就是这样:

$match = ORM::factory('match');
// fill Match with values
$match->result = MATCH_RESULT_WIN;
$match->started = time();
// save before using!
$match->save();

$player1 = ORM::factory('player')->where('name', '=', 'Federrer')->find();
$player2 = ORM::factory('player')->where('name', '=', 'Nadal')->find();
$player1->match = $match;
$player1->save();
$player2->match = $match;
$player2->save();

请注意,按关系设置时,应使用已保存的 ORM对象。

PS。你的关系对吗?一个玩家可以玩很多比赛,所以我会考虑另一个方案:

// Match belongs to player1&player2
$match->player1 = $player1;
$match->player2 = $player2;
$match->save();