0

We have plots and beans that can be planted into the plots.

I am absolutely determined to use the following to find all plots the owner has, with a bean inside them.

$plots = $this->Plot->findAllByOwnerAndBean_id(uid, '> 0');

However, it gives me the SQL WHEREPlot.owner= '15' ANDPlot.bean_id= '> 0'

This suggests it may be impossible, but I don't feel it's definitive. (potentially, even relevant as 2.2?) And it may be, so the question is two-fold:

How do I get what I want out of the findBy, and if I really can't, how could I avoid less code than the following, which I can confirm works?

$plots = $this->Plot->find('all', array(
     'conditions' => array(
        'owner'     => uid,
        'bean_id >' => 0
      )
    ));
Community
  • 1
  • 1
Vael Victus
  • 3,966
  • 7
  • 34
  • 55

1 Answers1

1

I don't see how it would be possible with magic methods (may work with DboSource::expression() but if its user input you'd have to sanitize it yourself). You can, however, just make a helper method in your model.

class Plot extends AppModel {

    public function findAllByOwnerAndBeanId($owner, $beanId) {
        return $this->find('all', array(
            'conditions' => array(
                'owner'     => $owner,
                'bean_id >' => $beanId,
             ),
        ));
    }

}

Edit: You may instead try the following, but note that it's not tested.

$ds = $this->Plot->getDataSource();
$plots = $this->Plot->findAllByOwnerAndBean_id($uid, $ds->expression('> ' . intval($userInputtedBeanId)));

May be better for Sanitize::escape() rather than intval.

tigrang
  • 6,767
  • 1
  • 20
  • 22
  • Sadly it seems there really is no way to do what I want. $ds-> didn't work, but thanks for the effort. As for defining the function, it eliminates my need for this. :P I'll push on with the find() and see if anyone has anything else to say. Thanks so much. – Vael Victus Aug 24 '12 at 21:19
  • Doesn't totally eliminate the need. It makes your code more re-usable and testable. Fatter models, skinnier controllers. – tigrang Aug 24 '12 at 23:24