2017-04-01 88 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);