Symfony2: Base table or view not found: 1146 - php

Problem
Hi, I"m working with a friend on a Symfony2 project. He's working on a Windows based computer and I'm on my Mac.
We setup the project and made the database model / entities (code first) on his computer. Now I wanted to start working on it as well so we did a SQL dumb to my localhost. I edited the parameters.yml to match my settings. The project can connect to the server.
But when I try to open a page where the database is used i get this error:
An exception occurred while executing 'SELECT t0.id AS id1, t0.name AS name2, t0.bigimage AS bigimage3, t0.smallimage AS smallimage4, t0.info AS info5, t0.city_id AS city_id6 FROM District t0':
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'socialgeogroep6.District' doesn't exist
500 Internal Server Error - DBALException
1 linked Exception: PDOException »
Just to be clear, the page is running normal on his computer; he gets the data as it should be.
Question
What can be the problem? I looked in my PHPmyAdmin over and over again and the database is there with all the fields and data...
(screen: http://gyazo.com/4a0e5f1ee6b1e29d2d277df5fc0d8aac)
I really can't imagine what the problem is.
I hope someone can help us!

It's likely a case issue. You have the district table on your database, but doctrine is asking for the District table.
You should configure doctrine to use lower case table name. Refer to the doctrine documentation http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#persistent-classes to know how to do so.

I just had exactly the same kind of problem because i'm writing code on windows and i need to deploy on linux.
The solution is to add in config.yml the line:
doctrine:
orm:
naming_strategy: doctrine.orm.naming_strategy.underscore

This work for my in symfony 2.7. Just put in config.yml:
doctrine:
# ...
orm:
# ...
entity_managers:
default:
naming_strategy: doctrine.orm.naming_strategy.underscore

Table name case issue
socialgeogroep6.District
It should be socialgeogroep6.district as per the screenshot. Check the Entity annotation.

A word of caution: Before reading this solution. This is strictly a solution for those who are trying to set up the framework.
I think since you are just starting to try out, what you could do is, drop database and then start everything afresh.
- mysql -uroot -proot
- show databases;
- drop database <dbname>;
Then, recreate the tables.
- app/console doctrine:database:create
- app/console doctrine:schema:create
A word of caution it might be a very BAD idea to do this in production environment if you have already created your controllers and data is already populated.

If you are using Orm, you can set up it like this
District.orm.yml
Project\Bundle\DuterteBundle\Entity\Vp:
type: entity
table: district//note the lowercase
repositoryClass: Project\Bundle\DuterteBundle\Repository\VpRepository

May be missed to add singular table name object.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mapping extends Model
{
protected $table = 'mapping';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'user_id', 'mapping', 'name'
];
}

Related

Problem with spatie/laravel-menu and spatie/laravel-persmissions

I'm using spatie/laravel-menu and spatie/laravel-persmissions in my laravel project.
I have created a permission, assigned it to a role, and assigned the role to my user. This works fine.
Then I have generated a menu the middleware way using a macro like so:
\Menu::macro('main', function () use ($request) {
return \Menu::new()
->withoutWrapperTag()
->withoutParentTag()
->setActiveClassOnLink()
->route('preparation', 'Anstehende Termine')
->route('postprocessing', 'Nachbereitung')
->routeIfCan('administrate', 'protocols', 'Protokolle')
->addItemClass('nav-link')
->setActive($request->url());
});
In my application I have two User models with different connections:
App\User; using connection_a with database db_a and
App\DirectoryA\User; using connection_b with database db_b
In the auth config the first one is defined, and using Auth::user()->can('administrate') works fine, even in the Middleware that defines the menu.
Since I have added the menu item via routeIfCan, I'm getting an error. It tells
Base table or view not found: 1146 Table 'db_b.permissions' doesn't exist (SQL: select permissions.*, model_has_permissions.model_id as pivot_model_id, model_has_permissions.permission_id as pivot_permission_id, model_has_permissions.model_type as pivot_model_type from permissions inner join model_has_permissions on permissions.id = model_has_permissions.permission_id where model_has_permissions.model_id = 1 and model_has_permissions.model_type = App\User)
What is going wrong here? It should use the App\User model. Placing a dd() at the point the framework throws the exception shows me the correct connection...
Please help.
this mean table permissions not exist on your database maybe you forgot to run php artisan migrate after install laravel-permission?
A member of spatie helped to solve the problem:
Under the hood, routeIfCan calls app(Gate::class)->allows($ability, $ablityArguments). I assume Gate behaves slightly different than Auth::user() when it comes to multiple guards.
I don't see much room in routeIfCan to add an additional $guard or $connection argument, so I suggest you use $menu->addIf(Auth::user()->can('administrate'), ...) instead.

Unknown database type enum requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it. Symfony

I created a fresh symfony4 project. Made user Entity using php bin/console make:user, then tried to migrate using php bin/console make:migration. But then the error pops up
In AbstractPlatform.php line 434:
Unknown database type enum requested,
Doctrine\DBAL\Platforms\MySQL57Platform may not support it.
The strange thing is the User entity doesn't have any enum type rather it has a json column of roles, I suppose this is the reason.
/**
* #ORM\Column(type="json")
*/
private $roles = [];
I have seen some answers for the similar question for laravel, But don't know how to fix it in symfony4.
Couldn't reproduce your issue. But anyway you can set up enum type in doctrine.yaml like
doctrine:
dbal:
.....
mapping_types:
enum: string
To fix this, you can register that type mapping on your migration:
DB::connection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
Also, you could register it on app\Providers\AppServiceProvider.php.
public function boot() {
// ...
DB::connection()
->getDoctrineSchemaManager()
->getDatabasePlatform()
->registerDoctrineTypeMapping('enum', 'string');
// ....
}
Source: https://github.com/doctrine/dbal/issues/3161#issuecomment-542814085

Laravel database connection: Selecting from database name in snake case

I'm starting to learn Laravel. I've run through the example instructions from the site successfully and now I'm trying a second run through and I'm running into an issue.
I'm trying to connect to a database called zipCodes and has one table called zipCodeDetails.
In my Laravel project I have a model containing the following code:
<?php
class ZipCodeDetails extends Eloquent {}
And in my routes.php file I have the following code:
Route::get('zipCodes', function (){
$zipCodes = ZipCodeDetails::all();
return View::make('zipCodes')->with('zipCodes', $zipCodes);
});
The error I'm running into is when I try to load the URL:
http://localhost:8888/zipCodes
In my browser I'm getting the error code:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'zipcodes.zip_code_details' doesn't exist (SQL: select * from `zip_code_details`)
There's nothing written in my code where I define the database zipCodes as zipcodes or the table zipCodesDetails as zip_code_details. Something in laravel is changing the database and table names.
Does anyone know why this is happening and how I can prevent it? I don't want to just rename the database or table names because while that may get me by in testing it's not a viable solution in practice.
Thanks!
This is the behaviour that uses if no table is being explicitly defined. In your ZipCodeDetails class, you can set the table name that this model will be using.
class ZipCodeDetails extends Eloquent
{
protected $table = 'zipCodesDetails';
}

Add a column to an existing entity in Symfony

I've been playing around with Symfony on my web server and I've been creating entity with doctrine for my database. I wanted to add a column to one of these entity... I wanted to do something like:
php app/console doctrine:modify:entity
Now I know that this command doesn't exists, but is there a way (without doing a whole migration) to simply add a column.
P.S. I know I could open the php file and textually add the column there and then update the schema, but I'm distributing this to some clients and I like a more "command-line-like" approach.
Actually, using Doctrine does not make sense at all to do something like you suggested.
Doctrine is a ORM (Object-Relational Mapping) tool. It means that you want to abstract the database from your PHP code, you delegate database stuff to Doctrine. Doctrine does a wonderful job on that area.
As you want to keep your customers/peers updated with the latest version of the model, you should use the Doctrine Migrations ( http://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html ). That's the way to manage database updates. Moreover, it gives you complete control on what to do when upgrading/downgrading the database. You could, e.g., set default values before you add the FK.
The steps for adding a new property on the class should be:
For Symfony 2:
modify the class by:
Acme\MyBundle\Entity\Customer and add the property you want;
Acme\MyBundle\Entity\Customer
or modify the doctrine file:
Acme/MyBundle/Resources/config/doctrine/customer.yml
run the console command (it will add the proper set/get in the class)
php app/console doctrine:generate:entities AcmeMyBundle:Customer
run the console command
php app/console doctrine:migrations:diff
run the console command (it will place a new file on app/DoctrineMigrations)
php app/console doctrine:migrations:migrate
When you're deploying the new version of the code, all you got to do is update the source code and run the command above.
For Symfony 3:
modify the class by:
Acme\MyBundle\Entity\Customer and add the property you want;
Acme\MyBundle\Entity\Customer
or modify the doctrine file:
Acme/MyBundle/Resources/config/doctrine/customer.yml
run the console command (it will add the proper set/get in the class)
php bin/console doctrine:generate:entities AcmeMyBundle:Customer
run the console command (update database)
php bin/console doctrine:schema:update --force
Add new Column in Existing entity on Symfony. I have the same problem are there . after I long research best solutions are there.
solution work on Symfony 4
Example:
Blog entity already created inside one name column are there and I want to add description column. so simple enter
php bin/console make:entity Blog
After run this command you want to add new column
You definitely DO want to open the PHP/XML/YML file where your entity is defined and add the column there. Then, you use the commandline and say
console doctrine:schema:update
That way, your entity definitions are in sync with the database and your database gets updated.
There is a pitfall on step php app/console doctrine:migrations:diff described above when using doctrine migrations.
You made changes in entity, all seems valid, but the command on creating migrations php app/console doctrine:migrations:diff says "No changes detected in your mapping information."
And you can't find where's the old database structure placed, search in files found nothing.
For me, the key was to clear Redis cache.
php app/console redis:flushdb
It happens because of config.yml
snc_redis:
clients:
default:
type: predis
alias: default
dsn: redis://localhost
doctrine:
query_cache:
client: default
entity_manager: default
namespace: "%kernel.root_dir%"
metadata_cache:
client: default
entity_manager: default
document_manager: default
namespace: "%kernel.root_dir%"
result_cache:
client: default
namespace: "%kernel.root_dir%"
entity_manager: [default, read] # you may specify multiple entity_managers
After that, migrations:diff reread all of entities (instead of taking outdated ones metadata from cache) and created the right migration.
So, the full chain of steps for modifying entities is:
Modify your entity class (edit Entity file)
Clear Redis cache of metadata ( php app/console redis:flushdb )
Create (and may be edit) migration ( php app\console doctrine:migrations:diff )
Execute migration ( php app\console doctrine:migrations:migrate )
Of course, your doctrine metadata cache may be not Redis but something else, like files in app/cache or anything other. Don't forget to think about cache clearing.
May be it helps for someone.
I found a way in which I added the new column inside YourBundle/Resources/Config/doctrine/Yourentity.orm.yml.
Then added getter and setter methods inside Entity class.
Then did php app/console doctrine:schema:update --force from console. It worked for me.
FOR SYMFONY3 USERS...
here you have to follow two steps to make changes in your entity
Step1: Open Your Entity File..For EX: "Acme\MyBundle\Entity\Book"
Current Entity is having few fields like:id,name,title etc.
Now if you want to add new field of "image" and to make change constraint of "title" field then add field of "image" with getter and setter
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=500)
*/
private $image;
And add getter and setter
/**
* Set image
*
* #param string $image
*
* #return Book
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getimage()
{
return $this->image;
}
To update existing field constraint of title from length 255 to 500
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=500)
*/
private $title;
Ok...You have made changes according to your need,And You are one step away.
Step 2: Fire this command in project directory
php bin/console doctrine:schema:update --force
Now,check your table in database ,It's Done!!
f you need to add a new field property to an existin entity you can use make:entity
$ php bin/console make:entity
Class name of the entity to create or update
"existingentity"
New property name (press to stop adding fields):
description
Field type (enter ? to see all types) [string]:
text
Can this field be null in the database (nullable) (yes/no) [no]:
no
New property name (press to stop adding fields):
(press enter again to finish)
information extracted from https://symfony.com/doc/current/doctrine.html
I think, you need to update your relation table manually to map the relations.
I found this:discussion
Again, We can generate entities from existing database, as a whole, but separately? :(
That's how it worked for me:
add new vars, setters and getters inside the existing class:
src-->AppBundle-->Entity-->YourClassName.php
update the ORM File:
src-->AppBundle-->Resources-->config-->doctrine-->YourClassName.orm.yml
run bash command:
php bin/console doctrine:schema:update --force

Propel Multiple Database Modeling

I've just started working with Propel and I love it, but I have a question regarding how to utilize multiple database connections. I know I can set stuff up in my schema to connect to multiple different databases, but I'm curious how to handle this in code.
The issue I have is multiple databases, and each of them has slightly different schemas with no data warehousing. As a result I have things resembling the following:
databaseName: westCoastUsers
table: users
column1: email
column2: password
column3: FirstName
databaseName: eastCoastUsers
table: users
column1: email
column2: password
column3: firstName
column4: lastName
Right now in PHP non-Propel version, I'm doing all this by hand, and switching databases manually as required. I'm hoping to streamline things a bit, and I'm curious how to model this. Is there a way I can just have something like eastCoastUser and westCoastUser models that each refer to the proper database/etc or am I trying to wedge in something not supported?
I read this: How to use two database in propel but am uncertain how to actually execute that in code.
Thanks for the help
In your schema files, you can provide a name for the class that represents your table. They do not have to use the same name as the table. You do this with the phpName attribute on the table element.
For example your schema.xml could contain something like this
<database name="westCoastUsers">
<table name="users" phpName="WestCoastUser">
...columns here...
</table>
...
</database>
<database name="eastCoastUsers">
<table name="users" phpName="EastCoastUser">
...columns here...
</table>
</database>
(edit, note that the name="westCoastUser" on the database element refers to the name of the database, not the classes with similar names)
Then at build time, propel will generate WestCoastUser, WestCoastUserQuery, WestCoastUserPeer, EastCoastUser, EastCoastUserQuery and, EastCoastUserPeer. Each class will connect using the database it was defined under in your schema.
I wrote this originally for symfony 1.2, but I believe it all applies.
I’m using Symfony 1.2.4 for this example.I have two databases, master and slave
If you are going to use multiple databases, there are a few things that you are going to need to do.
You will need separate schema files for both (master.schema.yml and slave.schema.yml)
To use build-sql and insert-sql, you will need multiple propel.ini files
You will need to add an attribute to your schema files to get them to build right
Step 1
Create the databases.yml with two separate connections:
dev:
propel:
param:
classname: DebugPDO
test:
propel:
param:
classname: DebugPDO
all:
propel:
class: sfPropelDatabase
param:
classname: PropelPDO
dsn: mysql:dbname=master;host=xxx.xxx.xxx.xxx
username: uname
password: pass
encoding: utf8
persistent: true
pooling: true
master:
class: sfPropelDatabase
param:
classname: PropelPDO
dsn: mysql:dbname=slave;host=xxx.xxx.xxx.xxx
username: uname
password: pass
encoding: utf8
persistent: true
pooling: true
Step 2
As mentioned you will need two schema files. Please notice that you will need to define a package attribute for the database that matches up to the tables, and in this case it is ‘lib.model.master’ for the master connection.
master.schema.yml
master:
_attributes:
package: lib.model.master
defaultIdMethod: native
my_table:
_attributes: { package: lib.model.master }
my_id: { type: INTEGER, size: '11', primaryKey: true, autoIncrement: true, required: true }
etc.....
slave.schema.yml
slave:
_attributes:
package: lib.model.slave
defaultIdMethod: native
auctionp:
_attributes: { package: lib.model.slave }
etc.....
Step 3
You will need to create separate propel.ini files. In this example I used propel-master.ini and propel-slave.ini. Each of these files need to be configured for their respective databases.
Step 4
You will need a good batch file to build your your databases using the propel tools. Mine looks like this:
From the application root:
symfony build-model; cp config/slave-propel.ini config/propel.ini; symfony propel:build-sql; symfony propel:insert-sql --no-confirmation; cp config/propel-master.ini config/propel.ini; symfony propel:build-sql; symfony propel:insert-sql --no-confirmation;
Step 5
You will need to clean out /lib/model if you already built your model using one database and are now doing a split. Deleting the files in the “map” and “om” directories and the root directory will help you avoid conflicts.
Step 6
To use the two databases in code, you will need to add a bit to the connection, like the following:
Example 1:
$object = self::doSelect($c, Propel::getConnection('master'));
Example 2:
$newObject->save(Propel::getConnection('slave'));
Example 3:
$con = Propel::getConnection("propel");
$sql = "ALTER TABLE runlinhp CHANGE class class_rat varchar(15)";
$stmt = $con->prepare($sql);
$stmt->execute();

Categories