General error: 1005 Can't create table `learning`.`users` - laravel-6.2

When migrating my DB this error appears, below is my code followed by the error that I am getting when trying to run the migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('city')->nullable();
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}

Error 1005 is related to foreign key.
make sure you have roles table already or it will run before creating user table on
php artisan migrate just place roles migration files before users by editing name of the file.
2019_12_07_000000_create_roles_table.php
2019_12_08_000000_create_users_table.php

Related

Multiple files for Doctrine Fixtures for Symfony 3

I'm using the bundle Doctrine:Fixtures to load an example of bbdd throw the Entitys and since I work alone in the project it's ok.
But now, I got a colleague in my project and we were wondering if it's possible to set up a different files for the loading.
I got my own file of fixtures associated in git and I don't want him modifying this file. I would like to have an special file just for him that will allows him to modify whenever he wants this file of fixtures. So, anyone can have his owns records in the init of the bbdd.
If it's not possible with multiple files, could be possible in another way?
http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html
You can load specific fixture files using the --fixture flag:
php app/console doctrine:fixtures:load --fixture=/src/BundleName/DataFixtures/ORM/Fixture.php
Or, you could add a Fixtures.php.dist file with some working examples, then use .gitignore to ignore Fixtures.php.
Then add a command into your build (or in composer scripts), and/or your documentation to copy this .dist file to Fixtures.php when checking out the project.
Another method if you're doing BDD is to create a Helper class that can be used in your Context to create and persist entities as you need them in tests. This would allow you to create only specifics needed for the test. All it really needs is the EntityManager so it may be simpler than pre-defining all the fixtures up front.
You can use Faker to generate realistic entities.
class AbstractFixtureHelper implements ContainerAwareInterface
{
/**
* #var Generator
*/
protected $faker;
/**
* #var ContainerInterface
*/
protected $container;
public function __construct()
{
$this->faker = Factory::create();
}
/**
* #param ContainerInterface|null $container
* #return void
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* #return EntityManager
*/
protected function getEntityManager()
{
return $this->container->get('doctrine.orm.entity_manager');
}
}
Then for different entities - in this example, a user:
class UserFixtureHelper extends AbstractFixtureHelper
{
public function createUser()
{
$user = new User();
$user->setEmail($this->faker->email);
$this->getEntityManager()->persist($user);
$this->getEntityManager()->flush();
return $user;
}
}
Then in your Context, inject the UserFixtureHelper and create directly in the scenario steps.
/**
* #Given there is a User who XXX
*/
public function thereIsAUser()
{
$user = $this->userFixtureHelper->createUser();
}

symfony 3 choice validation issue

I have a choice field (drop-down) which I want to validate against a DB table.
Essentially, if the value is in the query's results, it's valid.
It's not so clear to me how the callback reported in the Symfony guide works :(
However, I have a validation.yml file:
User\UserBundle\Entity\Group:
properties:
role:
- Choice:
groups: [signUp]
callback: [User\UserBundle\Entity\Group, getRoles]
The entity Group.php
class Group
{
/** #var int */
private $id;
//...
public static function GetRoles()
{
return ['admin', 'user'];
}
}
This example works fine but my issue comes when I try to get those values from the group repository GroupRepository.php
class GroupRepository extends EntityRepository
{
public function getRoles()
{
return $this->createQueryBuilder('r')
->getQuery()
->getResult();
}
}
What am I supposed to do at this stage? Is the approach I used correct or should I call the Group Repository directly in the validation.yml? Or am I totally way off?
As I understand it you are trying to get those options from the repository like:
...
callback: [User\UserBundle\Repository\GroupRepository, getRoles]
This won't work as the Repository needs to be initialized through the Doctrine ORM service.
I guess you have to create a custom Constraint class and ConstraintValidator where the later is configured as a service and gets the entity manager passed as argument.
See http://symfony.com/doc/current/validation/custom_constraint.html

sqlite2 artisan migrate fails SQLSTATE[HY000]: General error: 1 no such table: XXX

I like use sqlite for CRUD with Laravel 4.2 & artisan.
php artisan generate:migration create_XXX_table
Edit app/database/migrations/YYYY_MM_DD_HHMMSS_create_XXX_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateKeysTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('keys', function(Blueprint $table)
{
$table->increments('id');
$table->text('key_pub');
$table->text('key_private');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('keys', function(Blueprint $table)
{
//
});
}
}
of course, config for local and production enviroment are sqlite driver, and for use 'database' => storage_path().'/MYDATABASE.sqlite', MYDATABASE.sqlite it's only a file create with touch.
Also try, with not file MYDATABASE.sqlite but problem it's other.
[InvalidArgumentException]
Database does not exist.
On various articles on internet, show this method. Create a empty file, on rute.
But not work any.

Symfony2, Doctrine2, Entity Repository

We have such repository
class CronInfoCharacterInfoRepository extends EntityRepository
{
/**
* #param string|integer $characterID
* #return void
*/
public function add($characterID)
{
if (!$this->find($characterID)) {
$oEntry = new CronInfoCharacterInfo();
$oEntry->setCharacterID($characterID);
$this->getEntityManager()->persist($oEntry);
$this->getEntityManager()->flush();
}
}
}
But I want insert new entry by DQL. How can I do this through $this->createQueryBuilder()... ? And is it normal to use 'entity manager' inside repository?
You cant insert using DQL the very documentation says about that
INSERT statements are not allowed in DQL, because entities and their
relations have to be introduced into the persistence context through
EntityManager#persist() to ensure consistency of your object model.
http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html
And it is perfectly ok to use enitity manager inside Repo. What you are doing now is correct !

symfony 2 unique constraint validation with association

I'm having trouble validating the "uniqueness" of two fields, being one of them an entity of an association. The logic is that there can't be two taxes with the same description for a single country.
Here's my (failed) attempt:
/**
* #ORM\Entity
* #ORM\Table(name="taxes", uniqueConstraints={#ORM\UniqueConstraint(columns={"country_id", "description"})})
* #UniqueEntity(fields={"country", "description"})
*/
class Tax
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column()
*/
protected $description;
/**
* #ORM\Column(type="float")
*/
protected $value;
/**
* #ORM\ManyToOne(targetEntity="Country", inversedBy="taxes")
*/
protected $country;
//getters and setters...
}
When I test my app with a duplicate tax entity, the form pass the validation (when it shouldn't) and Symfony throws an error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-ITBMS' for key 'country_id'
UPDATE: I found that this is a known bug in Doctrine 2.1 that is fixed in Doctrine 2.2. Unfortunately, Symfony 2.0.11 (my current version) ships with Doctrine 2.1 and I don't know how to update my deps file appropriately
UPDATE 2: After updating my deps and deps.lock files to get the latest Doctrine 2.2.1 files as #elnur suggested below, the problem is still there: The composite unique key is created in the database but the validation is not correctly performed. Upgrading the Doctrine files alone is not solving the problem.
UPDATE 3: I even updated Symfony core to version 2.0.12 but it doesn't solve the problem either.
UPDATE 4 (SOLVED): I found the error inside my controller. Here is my original controller code:
public function createAction($country_id)
{
//...
if($request->getMethod() == 'POST')
{
$form->bindRequest($request);
$tax->setCountry($country); //HERE IS THE ERROR...
if($form->isValid())
{
//...
}
}
//...
}
Setting the country before binding the request was the solution.
public function createAction($country_id)
{
//...
if($request->getMethod() == 'POST')
{
$tax->setCountry($country); //NOW IT WORKS...
$form->bindRequest($request);
if($form->isValid())
{
//...
}
}
//...
}
To upgrade to Doctrine 2.2.1, replace related entries in your deps file with these:
[doctrine-common]
git=http://github.com/doctrine/common.git
version=2.2.1
[doctrine-dbal]
git=http://github.com/doctrine/dbal.git
version=2.2.1
[doctrine]
git=http://github.com/doctrine/doctrine2.git
version=2.2.1
And in your deps.lock with these:
doctrine-common 2.2.1
doctrine-dbal 2.2.1
doctrine 2.2.1
Then run:
bin/vendors install
UPDATE
Since upgrading Doctrine didn't work, try the UniqueEntityCaseInsensitive constraint from my ValidatorBundle.
Install the bundle, import the constraint:
use Elnur\ValidatorBundle\Validator\Constraints\UniqueEntityCaseInsensitive;
and replace your
#UniqueEntity(fields={"country", "description"})
with
#UniqueEntityCaseInsensitive(fields={"country", "description"})

Resources