Showing posts with label mysql. Show all posts
Showing posts with label mysql. Show all posts

Tuesday, October 16, 2012

Native SQL Query in Doctrine

Examples...
// get Doctrine_Connection object
$con = Doctrine_Manager::getInstance()->connection();
// execute SQL query, receive Doctrine_Connection_Statement
$st = $con->execute("...............");
// fetch query result
$result = $st->fetchAll();
Or with parameter...
$db = Doctrine_Manager::getInstance()->connection();
$query = $db->prepare("INSERT INTO search_term (term, counter) VALUES (:term, '1') ON DUPLICATE KEY UPDATE counter=counter+1;");
$query->execute(array('term' => $search));

Tuesday, January 4, 2011

Sort By Foreign Key or Custom Column in Symfony Admin Generator

This solution is works with Doctrine ORM.
  1. Put this to the backend module's actions.class.php
    protected function addSortQuery($query)
      {
        $rootAlias = $query->getRootAlias();
        if (array(null, null) == ($sort = $this->getSort()))
        {
          return;
        }
        $s = $sort[0];
        $fields = $this->varHolder->get('configuration')->getFieldsDefault();
        if ($fields != null)
        {
          $field = $fields[$s];
          if ($field != null)
          {
            if (isset($field['sortBy']))
            {
              $criterion = $field['sortBy'];
              if ($criterion != null)
              {
                $s = $criterion;
              }
            }
          }
        }
        
        if (isset($field['noRootAlias']) && $field['noRootAlias'] == true)
        {
          $query->addOrderBy($s . ' ' . $sort[1]);
        }
        else
        {
          $query->addOrderBy($rootAlias.'.'.$s . ' ' . $sort[1]);
        }
      }
    
  2. Let's see first the foreign key sorting with an example. If you want to show the related object's name instead of its id, you must use the relation name (in this case 'Group'). To enable sorting, add the sortBy parameter to the field.
    config:
          ...
          fields:
            name:    { label: Name }
            Group:   { label: Group, sortBy: Group.name }  
          list:
            title:   Users
            display: [id, name, Group]
    
    That's all, the sorting now works, but the column's name is not clickable yet. You have to change the generator's template. As I use the sfAdminThemejRollerPlugin, I will do this with that.
  3. Open the \ plugins \ sfAdminThemejRollerPlugin \ data \ generator \ sfDoctrineModule \ jroller \ template \ templates \ _list_th_tabular.php file and change the 4th row from this:
    <?php if ($field->isReal()): ?>
    to this:
    <?php if ($field->isReal() || $field->getConfig('sortBy')): ?>
    Now the foreign key sorting must work.
  4. Let's see the custom column sorting with an example. The data you will want to see in the custom column is somewhere in the database. You have to add your custom column to the original sql statement. Use joins, relations or simply subqueries. You can overwrite the sql in backend module's actions.class.php:
    protected function buildQuery()
      {
         $query = parent::buildQuery();
         // do what ever you like with the query    
         // use the die($query->getSqlQuery()); row to see the original sql statement
         return $query->addSelect('*, (SELECT foo FROM bar) as foobarcolumn');
      }
    As you can see I didn't change the query output, I only add an extra column to the query.
  5. Now we have to add this column to the generator.yml...
    config:
          ...
          fields:
            name:    { label: Name }
            Group:   { label: Group, sortBy: Group.name }
            foobar:  { label: FooBar, sortBy: foobarcolumn, noRootAlias: true }
          list:
            title:   Users
            display: [id, name, Group, foobar]
    
I hope this helps. The noRootAlias param is created by me, perhaps you won't need it or you can avoid using it. If you have an easier/better solution, please tell me!

Tuesday, December 14, 2010

Get the Auto_increment value of a Table in MySQL

SELECT auto_increment 
FROM information_schema.tables 
WHERE table_name='the_table_you_want';

Friday, September 3, 2010

Convert Table Character Set in Mysql

for example...
ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

Wednesday, September 1, 2010

How to Manage MySQL Table Names with #__ Prefix

Every time you make a query from a table that has a special #__ prefix, you need to put table name between `` signs.
INSERT INTO `#__session` ...
Otherwise it won't work and give you a meaningless error:

MySQL query error, please check your configuration! You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Tuesday, July 6, 2010

Select Items by the First Letter in MySQL

If you try to select items by the first letter and you want MySQL to deal with case sensitivity and accents, you have to collate the utf8_unicode_ci table to utf8_bin in this way...
SELECT * FROM thetable WHERE firstname COLLATE utf8_bin LIKE 'É%'

Wednesday, June 23, 2010

Create MySQL Dump to Save Data Before doctrine:build

If you use the symfony doctrine:build --all command, all data will be deleted in the database. To fix this, you have to save the data before the building and then import the dump file...
  1. mysqldump -t -c -u root -p DBNAME > dump.sql
  2. symfony doctrine:build --all
  3. mysql -u root -p DBNAME < dump.sql
Note: On Windows, you have to add the path (the mysql/bin directory) to the environmental variables.
Note2: The -t parameter removes the drop table and create table queries from the dump. It is needed if you change the structure of a table, otherwise drop table query will delete what symfony doctrine:build created.
Note3: The -c parameter adds the column names to INSERT INTO statements.