Search code examples
sugarcrmsugarbean

SugarQuery build up queryOr in a for loop


I am trying to build up a queryOr based on a comma separated list that is passed in by the user that I will loop over and add the values.

So far I got this which just builds it:

$query = new SugarQuery();
$query->from(BeanFactory::getBean('rdwrk_Request'));
$skills = $query->join('rdwrk_request_skills_rdwrk_request', array('alias' => 'skills'))->joinName();
$query->select(array(array('name', 'requestName'), array('skills.name', 'skillName')));
if($args["requestName"])
{
    $requestName = $args["requestName"];
    if(strpos($requestName, ',') !== false)
    {
        $requestNames = explode(",", $requestName);
        foreach($requestNames as $name)
        {
            $query->where()->queryOr()->contains('name', $name);
        }
    }
    else
    {
        $query->where()->contains('name', $requestName);
    }
}
if($args["skillName"])
{
    $query->where()->contains('skills.name', args["skillName"]);                
}
$results = $query->execute();

Is there any way to build it so all the values I loop over go into the same queryOr?


Solution

  • You can set the current SugarQuery object into its own variable, and then feed it through your loop as follows:

    $currentQuery = $query->where()->queryOr();
    foreach($requestNames as $name)
    {
        $currentQuery->contains('name', $name);
    }
    

    This calls the contains function on the same query object with the queryOr established. Since the $currentQuery variable references the same SugarQuery object, running $query->execute() later on will include the parameters.