我终于想进入数据模型。但是有一件事我不能包住我的头,我希望这听起来不会太愚蠢:关系模型对象奋斗
如何或何时设置对象的ID? 我的意思是,在创建对象时,无法知道该对象在插入数据库时(通过映射器类)时将具有的ID。那么,如果我不知道ID,我该如何坚持关系对象?
我会尝试通过一个例子来说明这一点:
class product {
private $id; // ??
private $name;
private $color;
function __construct($name, color $color){
$this->name = $name;
$this->color = $color;
}
function getName(){
return $this->name;
}
function getColor(){
return $this->color;
}
function setId(){
$this->id = $id;
}
}
class color {
private $id; // ??
private $hexCode;
function __construct($hexCode){
$this->hexCode = $hexCode;
}
function getId(){
return $this->id;
}
}
class productMapper{
function persist(product $product){
// persist query
$someQueryBuilder->insert('products')->set('name',$product->getName())->set('refColor',$product->getColor()->getId());
$product->setId($someQueryBuilder->getInsertId());
}
}
$color = new color('FFCC00');
$product = new product('table', $color);
$productMapper = new productMapper();
$productMapper->persist($product);
所以我的问题在这里,我不能坚持我product
对象,我color
对象没有ID呢。 什么是正确的做法? 或者我的方法在这里只是错误的?
感谢您帮助我,或者只是指引我走向正确的方向。