Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an INDEX with Doctrine 2 to a column without making it a primary key?

People also ask

Can I create index on any column?

No, you should not index all of your columns, and there's several reasons for this: There is a cost to maintain each index during an insert, update or delete statement, that will cause each of those transactions to take longer. It will increase the storage required since each index takes up space on disk.

How do I add an index to an existing table?

The following code block is an example to add index in an existing table. mysql> ALTER TABLE testalter_tbl ADD INDEX (c); You can drop any INDEX by using the DROP clause along with the ALTER command. Try out the following example to drop the above-created index.

What is it called when index is created on multiple columns then index?

A concatenated index is one index across multiple columns.


If you want to work with doctrine a table must have a primary key, see:

Every entity class must have an identifier/primary key. You can select the field that serves as the identifier with the @Id annotation.
Reference: Identifiers and Primary keys

To create an index: Annotations Reference

<?php
/**
 * @Entity
 * @Table(name="ecommerce_products",indexes={
 *     @Index(name="search_idx", columns={"name", "email"})
 * })
 */
class ECommerceProduct
{
}

Note that this is only being used if you generate the schema from your PHP code. So in case your table already exist you can also just add an index yourself.


When you use Doctrine and ORM:

@ORM\Table(indexes={@ORM\Index(name="name_idx", columns={"name"})})

If you're using Symfony with doctrine, you will also need to use the Index class in order for the annotation to work properly

use Doctrine\ORM\Mapping\Index;

Part of working code

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CountryRepository")
 * @ORM\Table(indexes={@ORM\Index(columns={"slug"})})
 */
class Country extends AbstractTrans implements SuggesterItem