A Symfony2 Query is returning all values in an array except one value which is a primary key of an another table. Both in CreateQueryBuilder and FindOneBy I'm not able to get the value but I can get all other values from the table. Why?
$repository123 = $em->getRepository('LoginLoginBundle:Clientuserdetails');
$client_userdetail = $repository123->createQueryBuilder('cud')
->where('cud.userid = ' . $userid)
->getQuery();
$clientuserdet = $client_userdetail->getResult();
Here userid is an entity in Clientuserdetails(). It refers to another table userdetails. Even I passed the userid in the query, I can get all the field values except userid.
Related
I have a query to find the sum of points for an individual player in a given tournament. It works well except that the value for the "User" is returned as the foreign key id for that user.
$q = $this->createQueryBuilder('s')
->select('IDENTITY(s.user) as user', 'SUM(s.points) as points')
->groupBy('s.user')
->andWhere('s.tournament = :tournament')
->setParameter('tournament', $tournament)
->orderBy('points', 'DESC')
;
Is there a way that I can select the user's username instead? I'd expect it's possible, instead of having to make another query for every user in the result.
Just join the user table and add username to select query:
$q = $this->createQueryBuilder('s')
->select('IDENTITY(s.user) as user', 's.username', 'SUM(s.points) as points')
->leftJoin('s.user','user')
->groupBy('s.user')
->andWhere('s.tournament = :tournament')
->setParameter('tournament', $tournament)
->orderBy('points', 'DESC');
I have a table of Customers with fields name, addressLine1, addressLine2 and postcode. The corresponding entity also has a method called address that returns the 2 address lines and the postcode concatenated together with comma/space separation, ignoring any empty fields.
I want to return a list of customers sorted by name and then address (for any customers with the same name). Currently I try
$this->getEntityManager()->createQuery(
'SELECT c FROM AppBundle:Customer c ORDER BY c.name ASC, c.address ASC'
)->getResult();
but I cannot use the method Customer::address() in the query like this. I get the error
Error: Class AppBundle\Entity\Customer has no field or association named address
Is there a way I can use an Entity's methods inside a query like this?
Short answer - no, and you don't really want to. You're conflating PHP logic with SQL logic. Your address() function is a pure PHP function. Even though it is using relationships within your entity, Doctrine itself has no way of knowing about it. Your function is literally returning a string, so how would it know how to convert that to SQL for your WHERE clause?
Just change your original query to this:
$this->getEntityManager()->createQuery('
SELECT c
FROM AppBundle:Customer c
ORDER BY c.name ASC, c.addressLine1 ASC, c.addressLine2 ASC, c.postcode ASC
')->getResult();
I suppose you could pseudo-do what you want like this:
Customer Entity:
public static function addressSort()
{
return ' c.addressLine1 ASC, c.addressLine2 ASC, c.postcode ';
}
and then do
$this->getEntityManager()->createQuery('
SELECT c
FROM AppBundle:Customer c
ORDER BY c.name ASC, ' . Customer::addressSort()
)->getResult();
However, now you're mixing PHP and SQL even further and I very highly recommend that you do NOT do this.
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;
}
I want add a new column with uniquie=true but every time get duplicate values '' , this column i want to be not null. How can i construct a migration to do that, i was try many ways but i read only if have my update query in function up this query will be loaded. but in function postUp i set my unique fields vales.
This i was trying but not working:
public function postUp(Schema $schema){
$users = $this->container->get('doctrine')->getRepository('AppBundle:Users')->findAll();
foreach($users as $user){
$user->setAffiliatesToken(uniqid().str_replace(' ','',str_replace('.','',microtime())));
}
$this->addSql('CREATE UNIQUE INDEX UNIQ_1483A5E952C22EB5 ON users (affiliates_token)');
$this->addSql('CREATE INDEX IDX_1483A5E99F12C49A ON users (affiliate_id)');
$this->container->get('doctrine')->getManager()->flush();
}
I have table called
tasks---id ,name,groupid
user----id,username , groupid
Now i have another table
userTasks with fields id,name, taskid , userid
Now i want that when the new user is created or persisted in database then
all the tasks with same groupid asuser should gets inserted in
usertasks table with taskid and userid
HOw can i do that
I am thinking of puting the logic in postFlush() event
But i don't know how doctrine first select and then insert the records in that table
If your do it just after of insert the data, instead inside postFlush function, could be more confortable and easy.
$om->persist($user);
$om->persist($task);
$om->flush();
$usertask = new UserTask($id, $name, $user->getId(), $task->getId());
$om->flush();
$om is the ObjectManager; EntityManager is deprecated in Doctrine last version.
If you want to use postFlush() function, maybe have to declare both id's as private variables to have the info.