2017-04-01 94 views
0

我终于想进入数据模型。但是有一件事我不能包住我的头,我希望这听起来不会太愚蠢:关系模型对象奋斗

如何或何时设置对象的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呢。 什么是正确的做法? 或者我的方法在这里只是错误的?

感谢您帮助我,或者只是指引我走向正确的方向。

回答

0

在id列的产品表中添加一个auto_increment主键。

0

正如你在这里计划的那样,你不需要产品或颜色的Id。

但是,如果您坚持为这些类设置Id(例如,如果您在数据库表中也有这些对象),则必须在这些类中规划一些代码以设置对象的Id。

class product { 

    private $id; 
    private $name; 
    private $color; 
    private static $last_id; 

    function __construct($name, color $color){ 
    $this->last_id++; 
    $this->id=$this->last_id; 
    $this->name = $name; 
    $this->color = $color; 
    } 

    function getName(){ 
    return $this->name; 
    } 

    function getColor(){ 
    return $this->color; 
    } 

    function getId(){ 
    return $this->id; 
    } 
} 

class color { 

    private $id; 
    private $hexCode; 
    private static $last_id; 

    function __construct($hexCode){ 
    $this->last_id++; 
    $this->id=$this->last_id; 
    $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);