Welcome Guest, Not a member yet? Register   Sign In
ActiveRecord for CodeIgniter: Rails-style model interactions
#90

[eluser]webthink[/eluser]
Hi everybody. Really been enjoying using this class. I'm sure I'll have questions from time to time but this time I thought I'd share a slight modification I made.

I needed to find a way to count records that matched a certain criteria. SELECT COUNT...WHERE... sort of thing.
$this->users->where('email',$email_str)->count(); would have worked perfectly well but I have this paranoid feeling that as soon as you start chaining where's to your query your controller begins to look a bit like a model.

I wanted something a bit more controller friendly so I created a dynamic function similar to the find_by_fieldname function, called find_count_by_fieldname so now my call ends up looking like $this->users->find_count_by_email($email_str); Not a whole lot different I know, but somehow it just sits a bit better with me having something like that in the controller.

Anyway here are the changes I made. I was using a ChromeIce's development version.

Code:
function __call ($method, $args)
    {
        $watch = array(
            'find_by_',
            'find_all_by_',
            'join_',
            'find_count_by_',
            'count_',
            'sum_',
            'average_',
            'concatenate_',
            'find_related_',
            'fetch_related_'
        );
[.....]

and just below the _find_by function I added

Code:
/**
     * _find_count_by
     *
     * Count records in table where condition is met.
     *
     * There are some special search terms that you can use for particular searches:
     * IS_NULL to find null or empty fields NOT_NULL to find fields that aren't
     * empty or null
     *
     *
     * @access    private
     * @param    string
     * @param    array
     * @return    object
     */
    function _find_count_by ($field, $args)
    {
        $field = $this->_table . '.' . $field;

        switch ( $args[0] )
        {
            case IS_NULL:
                $this->where($field . IS_NULL);
                break;
            case NOT_NULL:
                $this->where($field . NOT_NULL);
                break;
            default:
                $this->where($field, $args[0]);
        }


        return $this->count(null,( isset($args[1]) ) ? $args[1] : null, ( isset($args[2]) ) ? $args[2] : null );

    }


Messages In This Thread
ActiveRecord for CodeIgniter: Rails-style model interactions - by El Forum - 02-28-2008, 02:16 AM



Theme © iAndrew 2016 - Forum software by © MyBB