Monday, 29 October 2018

How to minimize code duplication in sql query?

I am working on the SQL query code in which I want to avoid the sql query duplication.

Below is the sql query code:

    switch ($y) {
        case 'l.text':
            $query->order('numeric_text ' . (strtolower($x) == 'DESC' ? 'DESC' : 'ASC') .
                ', ' . $y . ' ' . (strtolower($x) == 'DESC' ? 'DESC' : 'ASC'));
            break;
    }

In the above SQL Query code strtolower($x) == 'DESC' ? 'DESC' : 'ASC' is being used at two places. I am thinking to place a varibale there instead.

This is what I have tried:

    $sortOrder = (strtolower($x) == 'DESC' ? 'DESC' : 'ASC');

    switch ($y) {
        case 'l.text':
            $query->order('numeric_text ' . $sortOrder . ', ' . $y . ' ' . $sortOrder);
            break;
    }



Problem Statement:

I am wondering if there is any other better way, we can avoid sql query duplication.



from How to minimize code duplication in sql query?

No comments:

Post a Comment