Дата на доктрина 2 в клауза where (querybuilder)

Имам следния проблем: Искам клауза where, която проверява дали даден потребител е активен И дали има правилната дата.

Потребителят съдържа следното:

  • състояние
  • Начална дата
  • Крайна дата

Така че състоянието трябва да остане на 1, след което той трябва да търси състояние = 1 И текущата дата е между началната и крайната дата. В момента имам следното и работи добре. Но началната и крайната дата не са задължителни. Така че може да е NULL. Как мога да получа запитване като:

SELECT * 
FROM user/entity/user 
WHERE 
  state = 1 
  AND (
    (startdate <= CURRENT_DATE AND enddate >= CURRENT_DATE) 
    OR startdate == NULL 
    OR enddate == NULL
  )

, така че получавам всичките си активни потребители, а не само временните потребители.

В момента съм настроил следния код: Хранилище:

        public function searchUser($columns, $order_by, $order)
        {
            //Create a Querybuilder
            $qb = $this->_em->createQueryBuilder();
            
            //andx is used to build a WHERE clause like (expression 1 AND expression 2)
            $or = $qb->expr()->andx();
    
            //Select all from the User-Entity
            $qb->select('u')
               ->from('User\Entity\User', 'u');
            
            
            
            foreach($columns as $column => $name) 
            {                        
                if($column == 'state') 
                {
                    if($columns['state']['value'] == '1') {
                        $or = $this->betweenDate($qb, $or);
                        $or = $this->like($columns, $qb, $or);
                    } elseif($columns['state']['value'] == '2') {
                        $or = $this->like($columns, $qb, $or);
                    } elseif($columns['state']['value'] == '3') {
                        $or = $this->outOfDate($qb, $or);
                    }
                } else {
                    //Get a where clause from the like function
                    $or = $this->like($columns, $qb, $or);
                }
            }
            
            //Set the where-clause
            $qb->where($or);
    
            //When there is a order_by, set it with the given parameters
            if(isset($order_by)) {
                $qb->orderBy("u.$order_by", $order);
            }
             
            //Make the query
            $query = $qb->getQuery();
            
            /*echo('<pre>');
            print_r($query->getResult());
            echo('</pre>');*/
            
            //Return the result
            return $query->getResult();
     
        }
    
        public function betweenDate($qb, $or)
            {
                $or->add($qb->expr()->lte("u.startdate", ":currentDate"));
                $or->add($qb->expr()->gte("u.enddate", ":currentDate"));
                //$or->add($qb->expr()->orx($qb->expr()->eq("u.startdate", null)));
                $qb->setParameter('currentDate', new \DateTime('midnight'));
          
                return $or;
            }
        
    //This one works perfect
        public function like($columns, $qb, $or)
            {
                //Foreach column, get the value from the inputfield/dropdown and check if the value
                //is in the given label. 
                foreach($columns as $label=>$column){
                    $value = $column['value'];
                    $or->add($qb->expr()->like("u.$label", ":$label"));
                    $qb->setParameter($label, '%' . $value . '%');
                }
                
                return $or;
            }

Използвам това потребителско търсене и за други области. Така че трябва да избере всички данни от базата данни, само състоянието е различно, защото остарелите не са в базата данни. Така че трябва да се провери по различен начин. Надявам се някой да помогне.

Проблема решен

    $startdate = $qb->expr()->gt("u.startdate", ":currentDate");
        $enddate = $qb->expr()->lt("u.enddate", ":currentDate");
        
        $or->add($qb->expr()->orX($startdate, $enddate));

person Haidy    schedule 10.04.2013    source източник


Отговори (1)


Ето как бих изградил клаузата where:

    //CONDITION 1 -> STATE = 1
    $state = $qb->expr()->eq( 'state', ':state' );

    //CONDITION 2 -> startdate <= CURRENT_DATE AND enddate >= CURRENT_DATE
    $betweenDates = $qb->expr()->andX( 
        $qb->expr()->lte("u.startdate", ":currentDate"),
        $qb->expr()->gte("u.enddate", ":currentDate")
    );

    //CONDITION 3 -> startdate == NULL
    $startDateNull = $qb->expr()->isNull( 'startdate' );

    //CONDITION 4 -> enddate == NULL
    $endDateNull = $qb->expr()->isNull( 'enddate' );

    //CONDITION 5 -> <CONDITION 2> OR <CONDITION 3> OR <CONDITION 4>
    $dates = $qb->expr()->orX( $betweenDates, $startDateNull, $endDateNull );

    //CONDITION 6 -> <CONDITION 1> AND <CONDITION 5>
    $whereClause = $qb->expr()->andX( $state, $dates );
person lluisaznar    schedule 10.04.2013
comment
Благодаря, работи по този начин, в момента го имам така: $startdate = $qb->expr()->gt("u.startdate", ":currentDate"); $enddate = $qb->expr()->lt("u.enddate", ":currentDate"); $or->add($qb->expr()->orX($startdate, $enddate)); - person Haidy; 11.04.2013