Registering in ManyToOne with Doctrine

0

Oops, everyone, Personnel I have entities created a call of Products and another call of Categories they are related in type ManyToOne with Doctrine. In case it would be several products for a category. I already have registered several categories and precious include a product with a category. Ex:

Produto->nome: Camiseta Regata
Produto->valor: 11.0
Produto->categoria_id: 2

How do I make it include the data?

/**
 * @ORM\Entity(repositoryClass="JN\Models\Entity\ProdutoRepository")
 * @ORM\Table(name="produtos")
 */
class Produtos {
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue
 */
private $id;

/**
 * @ORM\Column(type="string", length=255)
 */
private $nome;

/**
 * @ORM\Column(type="string", length=255)
 */
private $descricao;

/**
 * @ORM\Column(type="decimal", precision=10, scale=2)
 */
private $valor;


/**
 * @ORM\ManyToOne(targetEntity="JN\Models\Entity\Categorias")
 * @ORM\JoinColumn(name="categoria_id", referencedColumnName="id")
 **/
private $categoria;

/**
 * @ORM\ManyToOne(targetEntity="JN\Models\Entity\Tags")
 * @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
 **/
private $tag;


/**
 * @return mixed
 */
public function getCategoria()
{
    return $this->categoria;
}

/**
 * @param mixed $categoria
 */
public function setCategoria($categoria)
{
    $this->categoria = $categoria;
}

/**
 * @return mixed
 */
public function getTag()
{
    return $this->tag;
}

/**
 * @param mixed $tag
 */
public function setTag($tag)
{
    $this->tag = $tag;
}

/**
 * @return mixed
 */
public function getId()
{
    return $this->id;
}

/**
 * @return mixed
 */
public function getNome()
{
    return $this->nome;
}

/**
 * @param mixed $nome
 */
public function setNome($nome)
{
    $this->nome = $nome;
}

/**
 * @return mixed
 */
public function getDescricao()
{
    return $this->descricao;
}

/**
 * @param mixed $descricao
 */
public function setDescricao($descricao)
{
    $this->descricao = $descricao;
}

/**
 * @return mixed
 */
public function getValor()
{
    return $this->valor;
}

/**
 * @param mixed $valor
 */
public function setValor($valor)
{
    $this->valor = $valor;
}

Thank you

    
asked by anonymous 26.01.2015 / 13:58

1 answer

1

First you have to search for Categoria (and create it, if it does not exist) and then bind Categoria to Produto .

// buscamos a categoria no bd
$categoria = $this->getCategoriaRepository()->findOneBy(['name' => 'tenis']);
if (!$categoria) {
    // se a categoria nao a existir, a criamos
    $categoria = new Categoria();
    $categoria->setName('tenis');
    $this->getManager()->persist($categoria);
}

// criamos o tenis
$tenis = new Tenis();
$tenis->setNome('Wave Nirvana');
// vinculamos o tenis à categoria
$tenis->setCategoria($categoria);
$this->getManager()->persist($tenis);

// salvamos tudo no bd
$this->getManager->flush();
    
26.01.2015 / 14:18