Doctrine ODM and schema-less design

后端 未结 2 1418
谎友^
谎友^ 2021-02-06 14:03

Continuing on from my question about EAV, I\'m considering using MongoDB to store product attributes.

I will store the catalogue part of this app - Categories, Products

2条回答
  •  再見小時候
    2021-02-06 14:06

    The solution is to use a @Hash

    Here is a VERY basic example I did up:

    id;
        }
    
        public function setName($name)
        {
            $this->name = $name;
        }
    
        public function getName()
        {
            return $this->name;
        }
    
        public function addAttribute($name, $value)
        {
            $key = preg_replace('/[^a-z0-9\ \_]/i', '', $name);
            $key = preg_replace('/\s+/i', '_', $key);
            $key = strtolower($key);
            $this->attributes[$key] = array('value' =>$value, 'label' => $name);
        }
    
        public function getAttribute($name)
        {
            return $this->attributes[$name];
        }
    
        public function getAttributes()
        {
            return $this->attributes;
        }
    
    }
    

    Add some data:

    setName('Cool Pen');
    $pen->addAttribute('Weight', 12);
    $pen->addAttribute('Ink Colour', 'Red');
    $pen->addAttribute('Colour', 'Black');
    
    $tv = new Product();
    $tv->setName('LED LCD TV');
    $tv->addAttribute('Weight', 12550);
    $tv->addAttribute('Screen Size', 32);
    $tv->addAttribute('Colour', 'Black');
    
    $dm->persist($pen);
    $dm->persist($tv);
    
    $dm->flush();
    

    Then query, find a product with the colour "Black" and a Screen Size greater than 20:

    createQueryBuilder('Catalogue\Product');
    $products = $query->field('attributes.colour.value')->equals('Black')
                    ->field('attributes.screen_size.value')->gte(20)
                    ->getQuery()->execute();
    

    I'm still not sure if this is a best way to do this and my research is still ongoing.

提交回复
热议问题