简体   繁体   中英

How to Join with Native SQL Query and doctrine

I'm developping an application with symfony 3.4. I want to execute a specific query. So i have two entities: the first is PrPurchaseRequest . the second is PrSpecificFieldValue .
PrPurchaseRequest has oneToMany prSpecificFieldValues .

I want to get id of purchaseRequest and prSpecificFieldValues

i did that

 $queryBuilder = $this->getEntityManager()->createQuery('select p.id as purchaseId, pr.keyField AS keyField,pr.ID AS prkeyvalueid from '.PrPurchaseRequest::class. ' p LEFT JOIN '. PrSpecificFieldValue::class .' spec ON p.id = spec.purchaseId ');

and that didn't work for me

[Syntax Error] Error: Expected end of string, got 'ON'

how can i do it

Using doctrine you need to play around your entities and their mappings with other entities in order to relate them like

use Doctrine\Common\Collections\ArrayCollection;

/** @Entity */
class PrPurchaseRequest
{
    /**
     * 
     * @OneToMany(targetEntity="PrSpecificFieldValue", mappedBy="prPurchaseRequest")
     */
    private $prSpecificFieldValues;
    // ...

    public function __construct() {
        $this->prSpecificFieldValues = new ArrayCollection();
    }
}

/** @Entity */
class PrSpecificFieldValue
{
    /**
     *
     * @ManyToOne(targetEntity="PrPurchaseRequest", inversedBy="prSpecificFieldValues")
     * @JoinColumn(name="pr_purchase_request_id", referencedColumnName="id")
     */
    private $prPurchaseRequest;
}

Now you have defined relationship between your entities you can join them based on their mapping (prSpecificFieldValues defined on PrPurchaseRequest class ) like

Its DQL (DQL != SQL)

SELECT p,v
FROM PrPurchaseRequest p
JOIN p.prSpecificFieldValues v

No need to specify ON clause doctrine will handle this for you.

One-To-Many, Bidirectional

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM