2017-04-01 1 views
0

마지막으로 데이터 모델을 사용하고자합니다. 하지만 내 머리를 감쌀 수없는 한 가지가 있습니다. 너무 바보 같이 들리지 않길 바래요.관계형 모델 객체 투쟁

개체 ID를 언제 또는 어떻게 설정해야합니까? 개체를 만들 때 (매퍼 클래스에 의해)이 개체가 데이터베이스에 삽입 될 때 어떤 ID가 있는지를 알 수있는 방법이 없습니다. 그렇다면 ID를 모른다면 관계형 객체를 어떻게 유지할 수 있습니까?

나는 예에 의해 이것을 설명하려고합니다 : 내 color 객체가 아직 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 개체를 지속 할 수 없다. 이 작업을 수행하는 올바른 방법은 무엇입니까 ?? 아니면 내 접근 방식이 잘못 되었습니까?

도와 주셔서 감사합니다. 아니면 저를 올바른 방향으로 안내해 주셔서 감사합니다.

답변

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);