Search code examples
phpmysqlredbean

Is it possible to rewrite this mySQL statement as a WHERE clause for redbean ORM?


based on How can I merge these mysql statements I have the following working sql statement:

SELECT *, max(DUP_NUMBER) as dup FROM table1 where  CONTACTS=1 GROUP BY FIELD_A ORDER BY date LIMIT 3

I am using the redbean ORM http://redbeanphp.com/finding_beans , which uses 'bean' objects to represent rows. I would like to use a specific method called findAll which requires that the assosciated sql query start with the WHERE keyword

$all = R::findAll('needle',' where $sql ');

It seems unlikely but I figured I would ask , given this constraint is there anyway to rewrite the entire query above into a WHERE SQL clause. something like:

" WHERE  max(DUP_NUMBER) as dup  where  CONTACTS=1 GROUP BY FIELD_A ORDER BY date LIMIT 3 "

THE "SELECT *" and " from table" are taken care of by the R::findAll. If this is impossible I will simply do it another way.

Thanks in advance,

Bill


Solution

  • If you click the SQL Query link on the "Finding Beans" page you referenced, you will find an example of retrieving beans with custom queries at the bottom:

    $sql = 'SELECT author.* FROM author 
            JOIN club WHERE club.id = 7 ';
        $rows = R::getAll($sql);
        $authors = R::convertToBeans('author',$rows);
    

    So for your case, it might look something like:

    $rows = R::getAll('SELECT *, max(DUP_NUMBER) as dup FROM table1 where  CONTACTS=1 GROUP BY FIELD_A ORDER BY date LIMIT 3');
    $all = R::convertToBeans('needle', $rows);
    

    assuming 'needle' is your bean type.