Inclusion of record in Manytoone with Doctrine

Asked

Viewed 49 times

0

Opa to all of you, Personal have created entities a call Products and another call Categories they are related in type Manytoone with Doctrine. In case it would be several products for one category. I have already 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 so 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

1 answer

1


First you have to fetch the Categoria (and create it if it does not exist) and then link to Categoria at the 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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.