Mykhailo YATSYSHYN
Mykhailo YATSYSHYN

Reputation: 179

Doctrine 2 reference table

I have the following problem. I have two tables

product
id|name|stock_status_id

stock_status
stock_status_id|language_id|name

I need to get object StockStatus in Product by stock_status_id. I use this code

    <?php

namespace OC\Model\Catalog\Product;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Class Product
 *
 * @ORM\Entity
 * @ORM\Table(name="oc_product")
 */
class Product
{
    /**
     * @var int
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer", nullable=false)
     */
    protected $product_id;

    /**
     * @var ArrayCollection
     * @ORM\OneToOne(targetEntity="StockStatus", mappedBy="stock_status_id")
     * @ORM\JoinColumn(name="stock_status_id", referencedColumnName="stock_status_id")
     */
    protected $stock_status;

I need a one-way relation, but the entry should return with the required language. How can I substitute there another dynamic value of the language?

Upvotes: 0

Views: 287

Answers (1)

user3267053
user3267053

Reputation: 166

Something like this is what you can do.

1- First update your Product entity class like this:

namespace OC\Model\Catalog\Product;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Class Product
 *
 * @ORM\Entity
 * @ORM\Table(name="oc_product")
 */
class Product
{
    /**
     * @var int
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer", nullable=false)
     */
    protected $product_id;

    /**
     * @ORM\OneToOne(targetEntity="StockStatus")
     * @ORM\JoinColumn(name="stock_status_id", referencedColumnName="stock_status_id")
     */
    protected $stock_status;
}

Just remove the Array Collection variable since this is a one to one relationship, there is not going to be an array there just an object of the StockStatus entity class.

2- Query to retrieve the StockStatus object from product from a specific language

public function GetStockStatusByLanguageId($languageId)
{
    $queryBuilder = $this->entityManager->createQueryBuilder();
    $queryBuilder->select('stock_status')
                 ->from('OC\Model\Catalog\Product', 'product')
                 ->join('product.stock_status', 'stock_status')
                 ->where($queryBuilder->expr()->eq('stock_status.language_id', $languageId));

    $result = $queryBuilder->getQuery()->getResult();
    return $result;
}

Assuming you have a repository for your Product entity class, this is a sample function. Just let me know if this is what you need.

Upvotes: 2

Related Questions