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

MysqlIndexingDoctrine Orm

Mysql Problem Overview


I want to add an index to a table column in my MySQL database. I am using Doctrine 2 to create my database schemas.

I know that I can use

/** @Id @Column(type="integer") */

to create primary keys. But my column shall neither have the unique nor the primary key attribute. It shall simply be an index in my table (MySQL knows these three types).

What is the proper statement to create such an index?

Mysql Solutions


Solution 1 - Mysql

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.

Solution 2 - Mysql

When you use Doctrine and ORM:

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

Solution 3 - Mysql

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;

Solution 4 - Mysql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGottlieb NotschnabelView Question on Stackoverflow
Solution 1 - MysqlFlipView Answer on Stackoverflow
Solution 2 - MysqlwebskyView Answer on Stackoverflow
Solution 3 - MysqlSamir PatelView Answer on Stackoverflow
Solution 4 - MysqlVasilii SuricovView Answer on Stackoverflow