I've 2 problems. I'm not sure if we can create one thread for 2 problems so let me know.
Add new indexes
I'm tring to add new indexes for performance, but it's create a new table User with new indexes
My code :
* User
*
* #ORM\Table(name="fos_user")
* #ORM\Table(indexes={#ORM\Index(name="last_activity_idx", columns={"last_activity"})})
* #ORM\Table(indexes={#ORM\Index(name="avatar_idx", columns={"avatar"})})
So I imagine, I must list all indexes in one #ORM\Table. But How ?
Error when I tried to update
When I tried to --force i've this error :
C:\wamp\www\ados>php app/console doctrine:schema:update --dump-sql
CREATE TABLE User (id INT AUTO_INCREMENT NOT NULL, profil_id INT DEFAULT NULL, username VARCHAR(255) NOT NULL, username_canonical VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, emai
l_canonical VARCHAR(255) NOT NULL, enabled TINYINT(1) NOT NULL, salt VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, last_login DATETIME DEFAULT NULL, locked TINYINT(1) NOT NULL,
expired TINYINT(1) NOT NULL, expires_at DATETIME DEFAULT NULL, confirmation_token VARCHAR(255) DEFAULT NULL, password_requested_at DATETIME DEFAULT NULL, roles LONGTEXT NOT NULL COMMENT
'(DC2Type:array)', credentials_expired TINYINT(1) NOT NULL, credentials_expire_at DATETIME DEFAULT NULL, user_ip VARCHAR(255) NOT NULL, name VARCHAR(16) NOT NULL, avatar VARCHAR(255) NOT
NULL, birthday DATE NOT NULL, sex TINYINT(1) NOT NULL, city SMALLINT NOT NULL, country SMALLINT NOT NULL, last_activity DATETIME NOT NULL, warning SMALLINT NOT NULL, status SMALLINT NOT
NULL, notification INT NOT NULL, visitor INT NOT NULL, friend INT NOT NULL, message INT NOT NULL, antiflood TINYINT(1) NOT NULL, autodestruction TINYINT(1) NOT NULL, suspended TINYINT(1
) NOT NULL, UNIQUE INDEX UNIQ_2DA1797792FC23A8 (username_canonical), UNIQUE INDEX UNIQ_2DA17977A0D96FBF (email_canonical), UNIQUE INDEX UNIQ_2DA17977275ED078 (profil_id), INDEX avatar_id
x (avatar), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE Verify (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, photo_id INT NOT NULL, status TINYINT(1) NOT NULL, date DATETIME NOT NULL, INDEX IDX_A6892F75A76ED395 (user_id)
, UNIQUE INDEX UNIQ_A6892F757E9E4C8C (photo_id), INDEX status_idx (status), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
ALTER TABLE User ADD CONSTRAINT FK_2DA17977275ED078 FOREIGN KEY (profil_id) REFERENCES profil (id);
ALTER TABLE Verify ADD CONSTRAINT FK_A6892F75A76ED395 FOREIGN KEY (user_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE Verify ADD CONSTRAINT FK_A6892F757E9E4C8C FOREIGN KEY (photo_id) REFERENCES photo (id) ON DELETE CASCADE;
DROP INDEX country_idx ON city;
CREATE INDEX name_idx ON city (name);
ALTER TABLE comment DROP FOREIGN KEY FK_9474526CA76ED395;
ALTER TABLE comment ADD CONSTRAINT FK_9474526CA76ED395 FOREIGN KEY (user_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE likes DROP FOREIGN KEY FK_49CA4E7DA76ED395;
ALTER TABLE likes ADD CONSTRAINT FK_49CA4E7DA76ED395 FOREIGN KEY (user_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE photo DROP FOREIGN KEY FK_14B78418A76ED395;
ALTER TABLE photo ADD CONSTRAINT FK_14B78418A76ED395 FOREIGN KEY (user_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE notification ADD CONSTRAINT FK_A765AD32F624B39D FOREIGN KEY (sender_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE notification ADD CONSTRAINT FK_A765AD32CD53EDB6 FOREIGN KEY (receiver_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE newsfeed ADD CONSTRAINT FK_2AEA5025F624B39D FOREIGN KEY (sender_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE visitor ADD CONSTRAINT FK_558D80370BEE6D FOREIGN KEY (visitor_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE visitor ADD CONSTRAINT FK_558D803CD53EDB6 FOREIGN KEY (receiver_id) REFERENCES User (id) ON DELETE CASCADE;
CREATE INDEX date_idx ON visitor (date);
ALTER TABLE bookmark DROP FOREIGN KEY FK_DA62921D5093B91;
ALTER TABLE bookmark DROP FOREIGN KEY FK_DA62921D707B33D2;
ALTER TABLE bookmark ADD CONSTRAINT FK_DA62921D5093B91 FOREIGN KEY (bookmarked_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE bookmark ADD CONSTRAINT FK_DA62921D707B33D2 FOREIGN KEY (bookmarker_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE ask ADD CONSTRAINT FK_506BAC00F624B39D FOREIGN KEY (sender_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE ask ADD CONSTRAINT FK_506BAC00CD53EDB6 FOREIGN KEY (receiver_id) REFERENCES User (id) ON DELETE CASCADE;
CREATE INDEX status_idx ON ask (status);
ALTER TABLE block DROP FOREIGN KEY FK_831B972244972A0E;
ALTER TABLE block DROP FOREIGN KEY FK_831B9722548D5975;
ALTER TABLE block ADD CONSTRAINT FK_831B972244972A0E FOREIGN KEY (victim_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE block ADD CONSTRAINT FK_831B9722548D5975 FOREIGN KEY (blocker_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE friend DROP FOREIGN KEY FK_55EEAC616A62BC6F;
ALTER TABLE friend DROP FOREIGN KEY FK_55EEAC6178D71381;
ALTER TABLE friend ADD CONSTRAINT FK_55EEAC616A62BC6F FOREIGN KEY (friend2_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE friend ADD CONSTRAINT FK_55EEAC6178D71381 FOREIGN KEY (friend1_id) REFERENCES User (id) ON DELETE CASCADE;
CREATE INDEX weight_idx ON category (weight);
ALTER TABLE follow DROP FOREIGN KEY FK_68344470A76ED395;
ALTER TABLE follow ADD CONSTRAINT FK_68344470A76ED395 FOREIGN KEY (user_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE post ADD CONSTRAINT FK_FAB8C3B3A76ED395 FOREIGN KEY (user_id) REFERENCES User (id);
CREATE INDEX date_idx ON post (date);
ALTER TABLE topic ADD CONSTRAINT FK_5C81F11FA76ED395 FOREIGN KEY (user_id) REFERENCES User (id);
CREATE INDEX home_idx ON topic (status, date);
ALTER TABLE report ADD CONSTRAINT FK_C38372B2A76ED395 FOREIGN KEY (user_id) REFERENCES User (id) ON DELETE CASCADE;
CREATE INDEX priority_idx ON report (priority);
ALTER TABLE log DROP FOREIGN KEY FK_8F3F68C5A76ED395;
ALTER TABLE log ADD CONSTRAINT FK_8F3F68C5A76ED395 FOREIGN KEY (user_id) REFERENCES User (id);
ALTER TABLE search DROP FOREIGN KEY FK_B4F0DBA7A76ED395;
ALTER TABLE search ADD CONSTRAINT FK_B4F0DBA7A76ED395 FOREIGN KEY (user_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE conversation ADD CONSTRAINT FK_92BFFD1156AE248B FOREIGN KEY (user1_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE conversation ADD CONSTRAINT FK_92BFFD11441B8B65 FOREIGN KEY (user2_id) REFERENCES User (id) ON DELETE CASCADE;
CREATE INDEX date_idx ON conversation (date);
ALTER TABLE message DROP FOREIGN KEY FK_B6BD307FA76ED395;
ALTER TABLE message ADD CONSTRAINT FK_B6BD307FA76ED395 FOREIGN KEY (user_id) REFERENCES User (id) ON DELETE CASCADE;
ALTER TABLE ban ADD CONSTRAINT FK_5AB3960544972A0E FOREIGN KEY (victim_id) REFERENCES User (id);
ALTER TABLE ban ADD CONSTRAINT FK_5AB39605684EC833 FOREIGN KEY (banner_id) REFERENCES User (id);
CREATE INDEX date_idx ON ban (date);
C:\wamp\www\ados> php app/console doctrine:schema:update --force
Updating database schema...
[Doctrine\DBAL\DBALException]
An exception occurred while executing 'ALTER TABLE comment ADD CONSTRAINT FK_9474526CA76ED395 FOREIGN KEY (user_id) REFERENCES User (id) ON DELETE CASCADE':
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`rencontreados`.`#sql-1be0_46`, CONSTRAINT `FK_9474526CA76ED3
95` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE)
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`rencontreados`.`#sql-1be0_46`, CONSTRAINT `FK_9474526CA76ED3
95` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE)
doctrine:schema:update [--complete] [--dump-sql] [--force] [--em[="..."]]
(sorry for the long text)
I understand it want to delete all indexes and recreated all of them. But I didn't delete default indexes created by doctrine like user_id FK, I juste want to add some because my website is slow. I'm completely lost...
Generally, your approach is valid. The thing with the FK constraints is that Doctrine sometimes can't resolve them itself.
You must open a MySQL shell and first deactivate FK checks:
SET FOREIGN_KEY_CHECKS = 0;
Then you must post the output of app/console doctrine:schema:update --dump-sql --complete into the same MySQL shell.
This should apply all pending updates (hopefully) without problems. Hint: concatenate all lines, so you'll see quickly in case there are warnings or errors.
After that, you can close the shell and run app/console doctrine:schema:update --dump-sql --complete again, to see if your database is in sync with the schema now.
Related
Am a novice please pardon me.
I have a users table with a 'UserId' column, this 'UserId' is foreign key to another table 'Calendar Table'. How do I send a post method from the calendar controller to post UserId from Users Table to Calendar Table?
dbo.calendar
[FileLength] BIGINT NOT NULL,
[CreationTime] DATETIME NOT NULL,
[LastUpdatedOn] DATETIME NULL,
[UserId] NVARCHAR (128) NOT NULL,
[ApplicationUser_Id] NVARCHAR (128) NULL,
CONSTRAINT [PK_dbo.CalendarTables] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.CalendarTables_dbo.User_ApplicationUser_Id] FOREIGN KEY ([ApplicationUser_Id]) REFERENCES [dbo].[User] ([Id]),
CONSTRAINT [FK_dbo.CalendarTables_dbo.User_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[User] ([Id])
dbo.users
[LockoutEnabled] BIT NOT NULL,
[AccessFailedCount] INT NOT NULL,
[UserName] NVARCHAR (256) NOT NULL,
[UserId] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.User] PRIMARY KEY CLUSTERED ([Id] ASC)
Calendar Controller
// POST api/value
[AllowAnonymous]
[ResponseType(typeof(CalendarTable))]
public IHttpActionResult PostCalendar(CalendarTable calendarTable)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.CalendarTables.Add(calendarTable);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = calendarTable.Id }, calendarTable);
}
I just need a method or a way to post a particular users 'UserId' from User Table to the 'UserId' of Calendar Table when a post request is made. Thanks
I am writing a Wordpress plugin extending Woocommerce that requires to store additional information about a user.
I understand that there is a separate wp_user_meta table specific to this, but I would rather use a custom table as I plan to use Wordpress/Woocommerce as an initial platform then hopefully expand to others. The data will also be queried often.
This custom table requires a single entry per user, defined by the ID in wp_user, therefore essentially being a one-to-one relationship. An example schema for the custom table is:
CREATE TABLE {$wpdb->prefix}custom_table (
custom_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id BIGINT UNSIGNED NOT NULL,
custom_data varchar(200) NULL,
FOREIGN KEY (user_id) REFERENCES wp_users(ID),
PRIMARY KEY (custom_id)
)
My question is using Wordpress, how do you ensure that the one-to-one relationship is maintained?
I know I will have to run an initial setup to create the entries in the custom table for existing users.
Other than this, are users allowed to change their ID at all in the user lifecycle? Is it a case of using registration/deletion hooks to ensure that the data in the custom table is up to date? (Or would the deletion cascade through to other tables when it happens in the wp_user table)
AFAIK, users can't change their IDs nor their usernames (because, well, that leads to a whole lot of issues) so you're fine in that regard.
Also, there are a few "gotchas!" you need to be aware of:
Your query will fail because user_id isn't being defined exactly the same way as the ID column in wp_users. You have: user_id BIGINT UNSIGNED NOT NULL. It should be: user_id BIGINT(20) UNSIGNED NOT NULL.
To make user_id sure is unique -and maintain the one-to-one relationship- you'll need to add UNIQUE(user_id) to your query.
Your table has to use the exact same storage engine. In your query, you're not defining a storage engine for it so MySQL will fallback to the default one, which might or might not be the same one used by the wp_users table. If it's not the same one, the query will -again- fail and your table won't be created.
Here's the revised query, assuming wp_users uses the MyISAM storage engine:
CREATE TABLE {$wpdb->prefix}custom_table (
custom_id bigint unsigned NOT NULL AUTO_INCREMENT,
user_id bigint(20) unsigned NOT NULL,
custom_data varchar(200) NULL,
FOREIGN KEY (user_id) REFERENCES wp_users(ID) ON DELETE CASCADE,
PRIMARY KEY (custom_id),
UNIQUE (user_id)
) ENGINE=MyISAM
If you want to make sure your table uses the exact same storage engine as the wp_users table -and you do- running this query before creating your table will tell you which one you need:
SELECT ENGINE
FROM information_schema.TABLES
WHERE TABLE_SCHEMA='{$wpdb->dbname}' AND TABLE_NAME='{$wpdb->users}';
For reference the code snippet - note that checks should be in place for checking the array size etc. but this gets me in the right direction. Thank you #cabrarahector
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
global $wpdb;
$query = "SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA='{$wpdb->dbname}' AND TABLE_NAME='{$wpdb->users}';";
$engine = $wpdb->get_results( $query )[0]->ENGINE;
$sql = "CREATE TABLE {$wpdb->prefix}custom_table (
custom_id bigint unsigned NOT NULL AUTO_INCREMENT,
user_id bigint(20) unsigned NOT NULL,
custom_data varchar(200) NULL,
FOREIGN KEY (user_id) REFERENCES wp_users(ID) ON DELETE CASCADE,
PRIMARY KEY (custom_id),
UNIQUE (user_id)
) ENGINE={$engine};";
dbDelta($sql);
this creates the custom table in the database
Suppose I have these tables:
CREATE TABLE "account" (
"id" INTEGER PRIMARY KEY
-- more fields
);
CREATE TABLE "product" (
"id" INTEGER PRIMARY KEY,
"accountId" INTEGER NOT NULL,
-- more fields
CONSTRAINT "fk_product_accountId" FOREIGN KEY("accountId") REFERENCES "account"("id") ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE "tag" (
"id" INTEGER PRIMARY KEY,
"accountId" INTEGER NOT NULL,
-- more fields
CONSTRAINT "fk_tag_accountId" FOREIGN KEY("accountId") REFERENCES "account"("id") ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE "product_tag" (
"productId" INTEGER NOT NULL,
"tagId" INTEGER NOT NULL,
PRIMARY KEY("productId", "tagId"),
CONSTRAINT "fk_tag_productId" FOREIGN KEY("productId") REFERENCES "product"("id") ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT "fk_product_tagId" FOREIGN KEY("tagId") REFERENCES "tag"("id") ON UPDATE CASCADE ON DELETE CASCADE
);
... in other words, an account can have products and tags associated with the account and can then associate these tags with those products.
Is there a way to define a constraint, at the database-level, that checks whether a product_tag combination is valid, i.e. whether the tag and product both belong to the same account, such that I can circumvent having to check this validity during an INSERT statement?
I thought about an additional column accountId in product_tag, but I don't think I can define multiple foreign keys on this, nor do I think this would actually check the constraint the way I intend.
Do CHECK constraints offer this level of complexity, perhaps?
How about this?
Account:
AccountID int not null
Tag:
AccountID int not null
TagID int not null
primary key (AccountID, TagID)
foreign key (AccountID) references Account(AccountID)
Product:
AccountID int not null
ProductID int not null
primary key (AccountID, ProductID)
foreign key (AccountID) references Account(AccountID)
ProductTag:
AccountID int not null,
TagID int not null,
ProductID int not null,
primary key(AccountID, TagID, ProductID)
foreign key(AccountID, TagID) references Tag(AccountID, TagID)
foreign key(AccountID, ProductID) references Product(AccountID, ProductID)
Using composite keys instead of identity keys on Tag and Product enables us to do this. I find using identity keys (surrogate keys) can have the effect of limiting the usefulness of constraints since the 'information' contained in the tables is more 'spread out', and constraints can only work on one or two tables, loosely speaking. I really like this scenario as an example of this effect. Using the first design would have forced us to use a trigger to enforce the rule.
I'm interested to see others' solutions on this...
A foreign key constraint cares only about the column(s) that are part of the constraint, so the only way to check the account ID would be to make it part of all keys.
CHECK constraints must not contain subqueries, so they cannot be used for this.
The only way to handle this with the existing database structure is a trigger:
CREATE TRIGGER check_product_tag_same_account
BEFORE INSERT ON product_tag
FOR EACH ROW
WHEN (SELECT accountId FROM product WHERE id = NEW.productId) !=
(SELECT accountId FROM tag WHERE id = NEW.tagId )
BEGIN
SELECT raise(FAIL, "account IDs do not match");
END;
I am trying to add a property in an entity in a third party bundle. Here is my yml file
Acme\Bundle\AppBundle\Entity\Group:
type: entity
table: pim_catalog_group_new
changeTrackingPolicy: DEFERRED_EXPLICIT
fields:
sortOrder:
type: integer
manyToOne:
family:
targetEntity: Pim\Component\Catalog\Model\FamilyInterface
joinColumn:
name: family_id
referencedColumnName: id
onDelete: 'SET NULL'
When i run the following command
php app/console doctrine:migrations:diff
It gives me id, family_id, sortOrder, code and other simple fields but associative fields from parent class are not included. Here is the produced migration script (Notice that oneToMany, manyToMany associative fields from parent are missing):
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE pim_catalog_group (id INT AUTO_INCREMENT NOT NULL, family_id INT DEFAULT NULL, code VARCHAR(100) NOT NULL, sortOrder INT NOT NULL, UNIQUE INDEX UNIQ_3196D4CB77153098 (code), INDEX IDX_3196D4CBC35E566A (family_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
$this->addSql('ALTER TABLE pim_catalog_group ADD CONSTRAINT FK_3196D4CBC35E566A FOREIGN KEY (family_id) REFERENCES pim_catalog_family (id) ON DELETE SET NULL');
$this->addSql('ALTER TABLE pim_catalog_group_translation DROP FOREIGN KEY FK_622D98DB7E366551');
$this->addSql('ALTER TABLE pim_catalog_group_translation ADD CONSTRAINT FK_622D98DB7E366551 FOREIGN KEY (foreign_key) REFERENCES pim_catalog_group (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE pim_catalog_association_group DROP FOREIGN KEY FK_E91414DDFE54D947');
$this->addSql('ALTER TABLE pim_catalog_association_group ADD CONSTRAINT FK_E91414DDFE54D947 FOREIGN KEY (group_id) REFERENCES pim_catalog_group (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE pim_catalog_group_product DROP FOREIGN KEY FK_7AC0C83AFE54D947');
$this->addSql('ALTER TABLE pim_catalog_group_product ADD CONSTRAINT FK_7AC0C83AFE54D947 FOREIGN KEY (group_id) REFERENCES pim_catalog_group (id) ON DELETE CASCADE');
}
As per #Rvanlaak suggestion:
PHP inheritance will not work in Doctrine as long as they aren't mapped using superclass or related. Especially once configuration formats (yml, annotation, xml) are mixed this will be tough, so easiest is to override the whole entity. Also see: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html
I ended up solving this problem by copying whole orm file into my custom bundle and modifying it to add my custom fields and associations.
From what I've gathered, Symfony 2 / Doctrine uses the database definitions (foreign key constraints in my case) to map relations between entities. I have two tables in particular that I want to be able to relate from both sides, but I do not want to create redundant foreign keys in each table. In this case, I have an Account table, and a Transaction table.
Account Table
CREATE TABLE "account" (
"account_id" BIGSERIAL NOT NULL,
"name" VARCHAR (100) NOT NULL,
"date_created" TIMESTAMP (6) WITH TIME ZONE NOT NULL,
"date_modified" TIMESTAMP (6) WITH TIME ZONE,
CONSTRAINT "pk-account-account_id"
PRIMARY KEY ("account_id"),
);
Transaction Table
CREATE TABLE "transaction" (
"transaction_id" BIGSERIAL NOT NULL,
"account_id" BIGINT NOT NULL,
"amount" MONEY NOT NULL,
"date_created" TIMESTAMP (6) WITH TIME ZONE NOT NULL,
"date_modified" TIMESTAMP (6) WITH TIME ZONE,
CONSTRAINT "pk-transaction-transaction_id"
PRIMARY KEY ("transaction_id"),
CONSTRAINT "fk-transaction-account_id-account-account_id"
FOREIGN KEY ("account_id")
REFERENCES "account" ("account_id")
ON DELETE RESTRICT
ON UPDATE CASCADE,
);
When I generate the entities using php bin/console doctrine:generate:entities I see that the transaction entity has an $account property, but my account entity does not have a $transaction entity. I assume this is because I do not define a foreign key constraint in my account table.
In my code, I create my account object by the following:
$accounts = $this->getDoctrine()
->getRepository('BalancesBundle:Account')
->findAll();
I then would want to iterate over the array to get the total balance for each account. In the long-term, I'd like to create a helper method inside my account entity that would call getTransactions() to add up all of the transactions into one sum total.
Is this possible? I feel like I'm missing something, and that my only recourse would be to do this from within the transaction entity. I would like to avoid doing this from the transaction entity if possible.
From what I get, you can't get transaction entities of the account entity. The weird thing is that you don't have "transactions" property inside your ccount entity, am I right ? Seems like a bad mapping.
Take a look at Doctrine documentation, you have to define your "transcations" property inside your "account" entity and map it with the OneToMany association.
Then you can use "php bin/console do:ge:entities AppBundle:Account"
If your entities are setup correctly then you should be able to access the transactions from the account.
foreach ($accounts as $account) {
$transactions = $account->getTransactions();
$transaction_total = 0;
foreach($transactions as $transaction) {
$transaction_total += $transaction->getAmount();
}
echo 'Transactions Total: '.$transaction_total;
}