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.
doctrine:generate:entitiesdoesn't generate entities from DB, but from mappings, so I assume you have created them first. Since you started with sql tables, I assume that you useddoctrine:mapping:importcommand. If you want to have bidirectional relation you should modify your mappings, not DB. Actually you should work with mappings and not DB.