multiple insertion in cakephp 3.8 - php

I should make a multiple listing. where two fields have the same values in common. For example, if I enter Inter, Milan, Juve they will have nationality_season and series_season as common fields. Furthermore, the user should decide on the number of advertisements to be made.
only that when I go to insert everything: Error: SQLSTATE[HY000]: General error: 1364 Field 'club_id' doesn't have a default value
i have this database
DROP TABLE IF EXISTS `championships`;
CREATE TABLE IF NOT EXISTS `championships` (
`id` int(11),
`club_id` int(11) NOT NULL,
`season` varchar(9) NOT NULL DEFAULT ' ',
`nationality_championship` varchar(50) NOT NULL DEFAULT '0',
`championship_series` varchar(50) NOT NULL DEFAULT '0',
`penal` int(11) DEFAULT '0',
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `clubs`;
CREATE TABLE IF NOT EXISTS `clubs` (
`id` int(11),
`name` varchar(35) NOT NULL DEFAULT ' '
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
ALTER TABLE clubs
ADD PRIMARY KEY (id),
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE championships
ADD PRIMARY KEY (id),
MODIFY id int(11) NOT NULL AUTO_INCREMENT,
ADD FOREIGN KEY(club_id) REFERENCES clubs(id);
the function that manages the insertion is the add function in the championships controller:
public function add()
{
$championship = $this->Championships->newEntity();
if ($this->request->is('post')) {
$championship = $this->Championships->patchEntity($championship, $this->request->getData());
if ($this->Championships->save($championship)) {
$this->Flash->success(__('The championship has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The championship could not be saved. Please, try again.'));
}
$clubsUnmated=$this->Championships->Clubs->find('list',['keyField' => 'id',
'valueField' =>['nome_societa']])->notMatching('Championships');
$this->set(compact('championship', 'clubsUnmated'));
}
extract code add.ctp:
<div class="championships form large-9 medium-8 columns content">
<?= $this->Form->create($championship) ?>
<fieldset>
<legend><?= __('Add Championship') ?></legend>
<?php
echo $this->Form->control('season',['class'=>'form-control']);
echo $this->Form->control('nazionalità_campionato',['class'=>'form-control']);
echo $this->Form->control('serie_campionato',['class'=>'form-control']);
echo $this->Form->control('club_id', ['options' => $clubsUnmated,'data-role'=>'tagsinput','type'=>'text','placeholder'=>'aggiungi squadre','class'=>'form-control']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>

For one thing, your form controls have different field names than your database schema is showing for nationality_championship and championship_series. That's not causing this problem, but it'll be a problem soon.
The main thing here is that it looks like you're going to be getting an array of values from your club_id, but the field in the database is a single value. If you want to stick with this database schema, you're going to have to loop over that array (which should probably be called something else in your form, to avoid issues when creating your entities to save). For example, if you rename that control to clubs, then it might look something like this:
if ($this->request->is('post')) {
$championships = [];
$data = $this->request->getData();
foreach ($data['clubs'] as $club_id) {
$championships[] = $this->Championships->newEntity(array_merge($data, compact('club_id')));
}
if ($this->Championships->saveMany($championships)) {
$this->Flash->success(__('The championship has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The championship could not be saved. Please, try again.'));
}
But even that probably isn't what you really want, as it's repeating the championship data many times in your database. I think what you really want is not to have club_id in that table at all, but rather have a championships_clubs join table, and then you can probably just name your club_id control as clubs._ids and your original patch and save code will work fine to create the whole record structure.

Related

Foreign key constraint when using drop down in CakePHP

I am using a drop down box with a foreign key relationship. I have got the drop down filling in the correct values but the only problem is when I add a user there is a foreign key constraint. But I can make users if I just use the normal input box and type an id that exists in the other table.
For example when I enter the id with this in my add.ctp, it works:
echo $this->Form->input('location');
but when I use this it doesn't
echo $this->Form->input('location_id', array('type' => 'select', 'options' => $CompanyLocations));
This is my add function in my UsersController
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$CompanyLocations= $this->Users->CompanyLocations->find('list');
$this->set(compact('CompanyLocations'));
$this->set(compact('user'));
$this->set('_serialize', ['user']);
This is in my UsersTable
$this->belongsTo('CompanyLocations');
and my CompanyLocationsTable
public function initialize(array $config)
{
parent::initialize($config);
$this->table('company_locations');
$this->displayField('location_name');
$this->primaryKey('location_id');
$this->belongsTo('Locations', [
'foreignKey' => 'location_id',
'joinType' => 'INNER'
]);
}
and my MySQL code
CREATE TABLE IF NOT EXISTS southpac_team.company_locations (
location_id INT NOT NULL AUTO_INCREMENT,
location_name VARCHAR(45) NULL,
PRIMARY KEY (location_id))
ENGINE = InnoDB;
DROP TABLE IF EXISTS southpac_team.users ;
CREATE TABLE IF NOT EXISTS southpac_team.users (
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(20) NOT NULL,
password VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
department INT NULL,
mobile VARCHAR(255) NULL,
email VARCHAR(255) NULL,
extension INT NULL,
lame_number INT NULL,
spa_auth_number VARCHAR(15) NULL,
creation_date DATE NULL,
picture VARCHAR(255) NULL,
employed TINYINT(1) NOT NULL,
location INT NOT NULL,
PRIMARY KEY (id),
INDEX get location_idx (location ASC),
CONSTRAINT get location
FOREIGN KEY (location)
REFERENCES southpac_team.company_locations(location_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Naming conventions
You are not following the naming conventions, by default the foreign key name for a belongsTo association is the singular underscored variant of the association alias, postfixed with _id so in the case of CompanyLocations that would be company_location_id, not just location.
echo $this->Form->input('company_location_id');
Also the variable holding the list should use camel casing, then you don't even need to specify it via the options argument:
$companyLocations= $this->Users->CompanyLocations->find('list');
$this->set(compact('companyLocations'));
Change the association defaults
If you are working with a legacy database that you cannot modify, then you need to configure CakePHP accordingly, ie specify the custom foreign key via the options argument of Table::belongsTo().
$this->belongsTo('CompanyLocations', [
'foreignKey' => 'location'
]);
Bake gets confused
The belongsTo association in CompanyLocationsTable looks fishy too, unless you really have a LocationsTable that should be associated with CompanyLocationsTable via:
company_locations.location_id > locations.primary_key
I guess you've created the model via bake, which treated location_id as a foreign key since it matches the default foreign key naming scheme for a belongsTo association.
See also
Cookbook > CakePHP at a Glance > Conventions > Model and Database Conventions
Cookbook > Database Access & ORM > Associations - Linking Tables Together > BelongsTo Associations
Cookbook > Views > Helpers > Form > Creating Form Controls
Cookbook > Views > Helpers > Form > Creating Inputs for Associated Data

How to avoid duplicate content stored in MySQL database submitted by user

I am creating a site that lets users list up to 5 companies they are associated with. When other users search these companies, all users associated with that company will show up in the search results.
The companies will be submitted by the users through a text input field.
How do I avoid users submitting duplicate companies? E.g. if UserA submits a company called stackoverflow, then UserB comes and also submits stackoverflow, there will be 2 stackoverflows in my database.
I have 3 tables:
Users Table
id|username|email
Company Table
id|company name
UsersCompany Table
id|userID|companyID
I'm using Laravel 5
You should really use Laravel Validation and keyword unique to handle this:
$this->validate($request, [
'company' => 'required|unique:company|max:255'
]);
Also, you could use custom Request class to handle form validation:
public function rules()
{
return [
'company' => 'required|unique|max:255'
];
}
If I were you, I'd use second one.
You can do it with a simple check. If the company does not exists create a new Company or attach the Company to the user.
I assume the companies are submitted in one single text input seperated by commas and you have setup your relations correct. If not check this.
Example:
// Inside your controller
public function post_something(Request $request)
{
// Always good to validate
$this->validate(....);
// Somehow get your user model
$user = ....
// Get companies input and loop
$company_names = $request->input('company_names');
$company_names = explode(',', $company_names );
foreach ($company_names as $company_name)
{
$company = Company::firstOrCreate(['company_name' => $company_name]);
$user->companies()->attach($company);
}
// Your other stuff
//
....
}
This can achieve this by
either creating PRIMARY Key or UNIQUE on company_Name
ALTER TABLE company_Table ADD PRIMARY KEY(company_Name)
ALTER TABLE company_Table ADD UNIQUE (company_Name)
or
IF NOT EXISTS(QUERY) Then INSERT
or
Create BEFORE INSERT trigger .
http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html
You can add a unique index on the table. So if your column is named company_name and table is companies you could execute the following:
alter table companies add unique (company_name)
Or alternatively you can do a query in programming before you allow an insert, which checks if the entry already exists. Or a combination of both..
you can use unique key for companies table
http://dev.mysql.com/doc/refman/5.7/en/constraint-primary-key.html
This is very easily obtainable, by using UNIQUE in MySQL.
ALTER TABLE `company_Table` ADD UNIQUE (
`company_Name`
)
By putting this into MySQL, the company_Name column becomes UNIQUE, meaning there can only be one. If you attempt to insert another one, an error returns.
UNIQUE can also be used on member emails on a userbase, if you don't want somebody to log in with the same email. UNIQUE is also perfect for POST_IDs, MEMBER_IDs, COMMENT_IDs, and several others, that could become very useful on a blog, forum, or social media site.
If you would like to create the UNIQUE key upon creating this table, here is how you would do so:
CREATE TABLE Company_Table
(
ID int NOT NULL,
Company_Name varchar(255),
UNIQUE (Company_Name)
)
W3schools has a good tutorial on this: Here
On my opinion you should use Eloquent firstOrCreate method
If you will use this approach, then you even no need any "unique" validation under the companies.
Lets start
DB Schema
users
id
username
companies
id
company_name
user_company
id
user_id
company_id
Models (only relations methods)
User.php
public function companies()
{
return $this->belongsToMany('NAMESPACE_TO_YOUR_MODEL\Company');
/*you can set foreign keys fields if it's not canonical see docs*/
}
Company.php
public function users()
{
return $this->belongsToMany('NAMESPACE_TO_YOUR_MODEL\User');
}
Controller
public function store(CompanyRequest $request)
{
$companiesFromRequest = $request->get('companies');
// it's just for example, you can retreive companies from request with any other approach
$companiesId = [];
foreach ($companiesFromRequest as $company) {
// assumes that $company variable contains all or at least part of info,
// that need to create or identify particuliar comapny
$c = Company::firstOrCreate($company);
$companiesId[] = $c->id;
}
// in this case we just retreive existing user
$user = User::findOrFail($request->get('user_id'));
$user->companies()->sync($companiesId);
// or you can use
// $user->companies()->attach($companiesId);
// difference between this commands you can found in official laravel docs
return redirect('any/place/you/wish')
}
Application Layer:
Use Laravel's Validation property 'unique' to establish that only unique company name is allowed.
public function store(Request $request)
{
$this->validate($request, [
'company_name' => 'required|unique:companies|max:255',
]);
// The company name is valid, store in database...
}
Database Layer:
add a constraint as unique to the migration of the company's table for company_name column.
$table->string('company_name')->unique();
found the answer in larval i just use firstOrNew() Creation Method
will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it:
as stated here
Try to build schema as following to get optimum performance.This structure helps you to avoid duplicate data and also do code validations in Laravel to avoid malicious inputs.
CREATE TABLE IF NOT EXISTS `Users Table` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `Company Table` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`company name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `company name` (`company name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `Users Company Table` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userID` int(11) unsigned NOT NULL,
`companyID` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `userID` (`userID`),
KEY `companyID` (`companyID`),
CONSTRAINT `Users Company Table_ibfk_1` FOREIGN KEY (`userID`) REFERENCES `Users Table` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `Users Company Table_ibfk_2` FOREIGN KEY (`companyID`) REFERENCES `Company Table` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
I hope this code helps you. This is a sql code to insert unique data
INSERT INTO UsersCompanyTable (userID, companyID)
SELECT * FROM (SELECT $_POST("user_id"), $_POST("company_id")) AS tmp
WHERE NOT EXISTS (
SELECT companyID FROM UsersCompanyTable WHERE companyID = $_POST("company_id")
) LIMIT 1;
You should allow user to select company, and then simply give reference of UserID, CompanyID tables in UsersCompany Table. So you will always have a unique record if UserA insert StackOverFlow and UserB also insert StackOverFlow, in your database. It will be like:
1-UserA-StackOverflow
2-UserB-StackOverFlow.
Or, if you want user to enter the company, check if the same company exists or not:
var checkcompany= "select * from Company Table where company name=company name"
Than check
if(checkcompany ! =null)
Than insert the record or else ignore it.

Inserting Record into Database with CakePHP Results in Foreign Key Violation

I'm now to CakePHP (a few days) and I'm having issues with inserting records with Foreign Keys.
Basic idea, Warehouses.
I have a warehouses table that holds all the available warehouses and I have a warehouse_types table to hold the different types of warehouses. The warehouse_types table already has some data in it.
I have a simple add view (based off the blog example in CakePHP's Cookbook) and I have it displaying the names of the different types from the database.
When I save the page I get a Database error.
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`kvs`.`warehouses`, CONSTRAINT `warehouses_ibfk_1` FOREIGN KEY (`warehouse_type_id`) REFERENCES `warehouse_types` (`id`))
The SQL that is being generated is:
SQL Query: INSERT INTO `kvs`.`warehouses` (`name`, `location`, `modified`, `created`) VALUES ('Name Text', 'Location Text', '2014-04-02 12:07:13', '2014-04-02 12:07:13')
If I output the information in the request->data object, it shows that it is getting a value for the warehouseType_id.
array(
'Warehouse' => array(
'name' => 'Name Text',
'location' => 'Location Text',
'warehouseType_id' => '1'
)
)
Any help on this would be awesome!
My database tables are as follows:
CREATE TABLE `warehouses` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`location` varchar(255) DEFAULT NULL,
`warehouse_type_id` int(10) unsigned NOT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `warehouse_type_id` (`warehouse_type_id`),
CONSTRAINT `warehouses_ibfk_1` FOREIGN KEY (`warehouse_type_id`) REFERENCES `warehouse_types` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
CREATE TABLE `warehouse_types` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
My models are as follows:
class Warehouse extends AppModel{
public $belongsTo = 'WarehouseType';
}
class WarehouseType extends AppModel{
}
My view (add.ctp) is as follows:
<h1>Add Warehouse</h1>
<?php
echo $this->Form->create('Warehouse');
echo $this->Form->input('name');
echo $this->Form->input('location');
echo $this->Form->input('warehouseType_id');
echo $this->Form->end('Create Warehouse');
?>
Finally, the add method in my WarehousesController:
public function add(){
//Check Request to see if it is a Post
if($this->request->is('post')){
$this->Warehouse->create(); //Make a new Warehouse object
debug($this->request->data);
if($this->Warehouse->save($this->request->data)){ //Try and save Warehouse
$this->Session->setFlash(__('Warehouse '.$this->request->data['Warehouse']['name'].' created'));
return $this->redirect(array('action' => 'index')); //Redirect back to Warehouse list
}
$this->Session->setFlash(__('Unable to add Warehouse :('));
}
$this->set('warehouseTypes', $this->Warehouse->WarehouseType->find('list'));
}
I've read over this answer here that seems the most relevant, but I'm lost: CakePHP Can't insert record with foreign key error
Also reviewed their documentation on saving: http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto
Your column name is different than what is being used in CakePHP. Change CakePHP to use warehouse_type_id. (Your CakePHP code is using warehouseType_id)
Change this- on your view file-
Add Warehouse
<?php
echo $this->Form->create('Warehouse');
echo $this->Form->input('name');
echo $this->Form->input('location');
echo $this->Form->input('warehouseTypes');
echo $this->Form->end('Create Warehouse');
?>

Creating a lookup field in a CakePHP form

I have a view created using Bake that has the following:
<fieldset>
<legend><?php echo __('Edit Device'); ?></legend>
<?php
echo $this->Form->input('DeviceID');
echo $this->Form->input('DeviceTypeID');
echo $this->Form->input('UserID');
echo $this->Form->input('Type');
echo $this->Form->input('KeyPadID');
echo $this->Form->input('Version');
echo $this->Form->input('Description');
echo $this->Form->input('UpdateID');
?>
</fieldset>
Which saves to the table:
CREATE TABLE `device` (
`DeviceID` VARCHAR(255) NOT NULL ,
`DeviceTypeID` INT(11) NOT NULL ,
`UserID` INT(10) NOT NULL ,
`Type` VARCHAR(10) NULL DEFAULT NULL ,
`KeyPadID` INT(10) NULL DEFAULT NULL ,
`Version` VARCHAR(255) NULL DEFAULT NULL ,
`Description` TINYBLOB NULL ,
`UpdateID` INT(11) NULL DEFAULT NULL ,
PRIMARY KEY (`DeviceID`),
INDEX `FK_USER` (`UserID`),
INDEX `FK_devices_updates` (`UpdateID`),
INDEX `FK_device_devicetype` (`DeviceTypeID`),
CONSTRAINT `FK_device_devicetype` FOREIGN KEY (`DeviceTypeID`) REFERENCES `devicetype` (`DeviceTypeID`),
CONSTRAINT `FK_devices_updates` FOREIGN KEY (`UpdateID`) REFERENCES `update` (`ID`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `FK_USER` FOREIGN KEY (`UserID`) REFERENCES `user` (`UserID`) ON UPDATE CASCADE ON DELETE CASCADE
)
My problem is that when the form is displayed, it shows DeviceTypeID and UserID as well as UpdateID as the foreign key value instead of a drop down with the caption being the text and the value being the ID column. How would I go about setting a field from the foreign table to be the display field and the id as being the value?
Update 11-02-2013
First of all I strongly suggest to convert your primary and foreign keys accordingly
so that they meet the CakePHP naming conventions.
This means that:
DeviceID should be id.
DeviceTypeID should be device_type_id
UserID should be user_id
Also all primary keys in your tables should be named as id.
This way you will never have to worry about anything, concerning your models etc.
After that, all your tables must be in plural form. This means that device table should be devices, so you should rename it also.
I assume that you also have the following tables: devices_types and users.
At this point, I should notice that I would prefer to have a table named devicetype. I avoid underscored names, because it's very easy to make mistakes using the correct form for each object, class etc. So I don't have to worry whether I should use the CamelCase or not.
Anyway
Your Device model should be something like that:
<?php
/** Device.php **/
class Device extends AppModel {
public $name = 'Device';
public $belongsTo = array(
'DeviceType' => array(
'className' => 'DeviceType',
'foreignKey' => 'device_type_id'
/** Specify other keys that meet your needs **/
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
};
?>
Also your DeviceType model should be similar to
<?php
/** DeviceType.php **/
class DeviceType extends AppModel {
public $name = 'DeviceType';
};
In your edit() method, you should query your DeviceType in something like this:
...
$devicetypes = $this->Device->DeviceType->find('list', array('id', 'caption'));
$this->set(compact('devicetypes'));
...
This way in your view the respective form element sets the <select> menu correctly.
PS: You should follow the CakePHP conventions about model-naming etc... Mine was just an example.

adding checkbox array to kohana orm validate

Having trouble adding checkbox values to db via orm
Working for normal fields but not if more than one checkbox is selected on the checkbox questions that allow more than one option
Here is the Form bit
<?php echo Form::label('first_name', 'First Name')?><br />
<?php echo Form::input('first_name', $profile->first_name, array('class'=>'inputbox')); ?><br />
<?php echo Form::label('last_name', 'Last Name')?><br />
<?php echo Form::input('last_name', $profile->last_name, array('class'=>'inputbox')); ?><br />
Favorite Genres:
<label><input type="checkbox" value="Horror" name="genres[]" />
<strong>Horror</strong></label><br />
<label><input type="checkbox" value="Thriller" name="genres[]" />
<strong>Thriller</strong></label><br />
Here is the controller bit
if ($_POST) {
if ($profile->values($_POST)->check()) {
$profile->user_id = $user;
$profile->save();
}
}
And Here is the Model bit
protected $_rules = array(
'first_name' => array(
'not_empty' => NULL,
),
'last_name' => array(
'not_empty' => NULL,
),
);
Only not working when more than one checkbox is selected, I get this error
Database_Exception [ 1241 ]: Operand should contain 1 column(s)
Not sure best approach for this.. Should I serialize or implode ? Where to do this?
I want to build basic search form in future to search 'like' values using this column.
This is an DB exception, not a Validation. You should use ORM relations for this situation:
class Model_Profile extends ORM {
protected $_has_many = array(
// profile has and belongs to many genres
'genres' => array(
'through' => 'profiles_genres', // pivot table name
),
);
}
And then change genres for current profile, like this:
try
{
$profile->check();
$profile->save();
// now replace old genres with a new list
// clear genres
$profile->remove('genres');
foreach($this->request->post('genres') as $genre)
{
$genre = ORM::factory('genre')->where('name', '=', $genre);
if ($genre->loaded())
{
$profile->add('genres', $genre);
}
}
}
catch (Validate_Exception)
{
// wrong input
}
Note that not genres are separated table, not a profiles column. Also you will need a pivot table profiles_genres with profile_id and genre_id columns.
You should create a genres table and model and create a pivot table for genres and profiles:
CREATE TABLE IF NOT EXISTS `genres` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `genres_profiles` (
`profile_id` int(10) UNSIGNED NOT NULL,
`genre_id` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`profile_id`,`genre_id`),
KEY `fk_genre_id` (`genre_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Note that you don't need to create ORM model for pivot table.
You can find more in the official docs

Categories