Symfony - Doctrine - Select query with a user (but can be anonymous user) - php

I'm using symfony 3, and I'm storing some data to database.
For this, the user does not have to be logged in.
Now I've created a select query with $this->getUser();. But the User can be NULL. When I execute this query, it does not select any rows.
return $this->createQueryBuilder('product')
->where('product.user = :user')
->andWhere('product.product = :product')
->andWhere('product.cartId = :uniqueCartId')
->setParameters([
'product' => $product,
'user' => $user,
'uniqueCartId' => $uniqueCartId
])
->getQuery()
->execute();
$user = $this->getUser();
I already tried this:
if(!$user instanceof User) $user = NULL;
But that does not work.
If I remove the User check, it works.
Any ideas?

I guess you should bind the where clause if there is an user object like
$parameters=array(
'product' => $product,
'uniqueCartId' => $uniqueCartId
);
$user = $this->getUser();
$query = $this->createQueryBuilder('product')
->where('product.product = :product')
->andWhere('product.cartId = :uniqueCartId');
if($user != null){ /* if($user instanceof User) */
$parameters['user'] = $user;
$query = $query->andWhere('product.user = :user');
}else{
/* $query = $query->andWhere('product.user IS NULL'); Not necessary */
}
$query->setParameters($parameters)
->getQuery()
->execute();

Related

Replace Having Cause with Where Clause

Please i have some trouble in my project in symfony
How can i replace having clause wuíth where clause in this code above cause having clause dont work white paginator in symfony
...
...
public function getAllClients($all = true, $user = null)
{
$qb = $this->_em->createQueryBuilder();
//
$qb->select('u, count(ls.id) as nbr')
->from($this->_entityName, 'u')
->join(Client::class, 'c', Join::WITH, 'c.user = u.id')
->join(LicenceShop::class, 'ls', Join::WITH, 'ls.client = c.id')
->groupBy('u.id')
->having('nbr > 1');
$qb->andWhere('u.roles LIKE :roles');
$qb->setParameter('roles', '%"ROLE_CLIENT"%');
return $qb->getQuery();
}
Thanks you
When i use having clause symfony response like that
Cannot count query that uses a HAVING clause. Use the output walkers for pagination
And this the function
enter code public function show($id = null, UserRepository $userRepository, Request $request, PaginatorInterface $paginator)
{
if($id)
$user = $userRepository->find($id);
else
$user = $this->getUser();
$client = $user->getClientInfo();
$myClients = $userRepository->getAllClients(false, $user);
$myClients = $paginator->paginate(
$myClients,
$request->query->getInt('page_c', 100)
);
$referal = null;
$licences = null;
if ($client) {
$referal = $client->getReferal();
$licences = $client->getLicences();
}
//$licences = $module->getLicences();
return $this->render('resellers/show.html.twig', [
'controller_name' => 'ResellersController',
'user' => $user,
'client' => $client,
'referal' => $referal,
'licences' => $licences,
'my_clients' => $myClients,
]);
}

How to update in one to one relation in laravel?

In my user model, I have the following code
public function profile()
{
return $this->hasOne(UserProfile::class);
}
In profile model,
public function user()
{
return $this->belongsTo(User::class);
}
The create method is working, But when I try to update the profile with following code, It is creating a new profile and doesn’t update the profile information.
$profile = new UserProfile();
$profile->dob = '1999-03-20';
$profile->bio = 'A professional programmer.';
$profile->facebook = 'http://facebook.com/test/1';
$profile->github = 'http://github.com/test/1';
$profile->twitter = 'http://twitter.com/test/1';
$user = User::find($userId);
$res = $user->profile()->save($profile);
What is the correct method to update in One to One Relationship ?
I fixed it using push method. Here is the code.
$user = User::find($userId);
$user->name = "Alen";
$user->profile->dob = '1999-03-20';
$user->profile->bio = 'A professional programmer.';
$user->profile->facebook = 'http://facebook.com/test/1';
$user->profile->github = 'http://github.com/test/1';
$user->profile->twitter = 'http://twitter.com/test/1';
$user->push();
You're doing right, however i could suggest a little improvement
You may use the following
$user = User::with('profile')->findOrFail($userId);
if ($user->profile === null)
{
$profile = new UserProfile(['attr' => 'value', ....]);
$user->profile()->save($profile);
}
else
{
$user->profile()->update(['attr' => 'value', ....]);
}
you are using save method to save new record. use update query
//controller
$userObj=new User();
if(!empty($userId) && $userId!=null){
$userObj->updateByUserId($userId,[
'dob' = '1999-03-20';
'bio' = 'A professional programmer.';
'facebook' = 'http://facebook.com/test/1';
'github' = 'http://github.com/test/1';
'twitter' = 'http://twitter.com/test/1';
]);
}
//model
function updateByUserId($userId,$updateArray){
return $this->where('user_id',$userId)->update($updateArray);
}

Symfony - query sum

I am writing a query which will return amount of total spent money for that user. Total spent = sum of all transaction amounts, where type = spend. I have set my type field in a base to 'spend'..
It returns
Invalid parameter: token type is not defined in the query.
My code.
public function getTotal(User $user, $type)
{
$query = $this->getSpendingRepository()
->createQueryBuilder('p')
->select("sum(p.amount) as total_amount")
->where('p.type = :spend')
->andWhere('p.user = :user')
->setParameters(['user' => $user,
'type' => $type])
->getQuery()
->getOneOrNullResult();
return $query;
}
and this is sql that is working so I don't know what am I doing wrong..
select user_id, sum(amount) as amount
from transaction
where type = 'spend'
group by user_id
Replace
->where('p.type = :spend')
with
->where('p.type = :type')
I fixed it.
public function getTotalSpent(User $user, $type = 'spend')
{
$query = $this->getTransactionRepository()
->createQueryBuilder('p')
->select("sum(p.amount) as total_amount")
->where('p.type = :type')
->andWhere('p.user = :user')
->setParameters(['user' => $user,
'type' => $type])
->getQuery()
->getOneOrNullResult();
return $query;
}

Symfony2 AJAX problems, response returns not refreshed data

I'm working with Symfony2 and AJAX and have some problems, my controller returns old data from database. I tried var_dump variable before returning and everything was fine, but JsonResponse returns old data.
My controller:
public function returnOrderAction(Request $request)
{
$id = $request->request->get('id');
$em = $this->getDoctrine()->getManager();
$bookEntity = $em->getRepository('BooksBundle:Book')->find($id);
$user = $this->getUser()->getId();
$this->get('order.complete')->returnOrder($bookEntity, $user);
$quantity = $bookEntity->getQuantity();
if (!$bookEntity) {
throw $this->createNotFoundException('Unable to find Book entity.');
}
return new JsonResponse(array(
'quantity' => $quantity,
), 200);
order.complete service:
public function returnOrder(Book $bookEntity, $userId)
{
$dq = $this->entityManager->createQueryBuilder('o')
->update('BaseBundle:Order', 'o')
->set('o.status', ':status')
->where('o.book = :id')
->andWhere('o.user = :user')
->andWhere('o.status = \'active\'')
->setParameter('status', 'done')
->setParameter('id', $bookEntity)
->setParameter('user', $userId)
->setFirstResult(0)
->setMaxResults(1)
->getQuery();
$dq->execute();
$this->entityManager->getRepository('BooksBundle:Book')->updateQuantityPos($bookEntity);
}

How to get last id for relationships in a transaction between models in Codeigniter?

I have this code inside a function in user-controller. I'm, using Codeigniter.
$name_user = $this->input->post('contact-company');
$company_name = $this->input->post('name-company');
$company_orgnr = $this->input->post('orgnr-company');
$phone_company = $this->input->post('phone-company');
$email_company = $this->input->post('email-company');
//Insert a a new user
$user_info = array(
'username' => $email_company,
'name_user' => $name_user
);
$company_info = array(
'name' => $company_name,
'orgnr' => $company_orgnr,
'phone' => $phone_company,
'email' => $email_company
);
//Insert a new user in db
$query_insertuser = "START TRANSACTION";
//Get sql for inserting a new user
$um = new Usermodel();
$query_insertuser .= $um->getSQLInsert($user_info);
//Get sql for inserting a new company
$cm = new Companymodel();
$query_insertuser .= $cm->getSQLInsert($company_info);
//Get sql for inserting relation between user
//and company (How do I get ID of user and ID of company to use?)
$upm = new Userprofilemodel();
$query_insertuser .= $upm->getSQLInsert();
$query_insertuser .= "COMMIT";
//Do the atual insert
$um->insert($query_insertuser);
It's used for handling a registration through a form. (Validation is done through the form-validation libray)-
Users with username, name_user is stored in a users-table
Companies are stored in a companies-table
Relations between companies and users are stored in a
userprofile-table
I think the code is kind of self-explainatory, but I'm not clear in how to insert the relation in the userprofile-model. I do need the last inserted id for user and the last inserted id for company, but in my code I don't have that because I don't actually insert any users or companies before calling $upm->getSQLInsert();
Or am I doing this incorrectly? Please give me any pointers...
I was obviously not doing this correctly. In case anyone care to bother this is my solution:-)
User-controller (part of it)
//Insert a new user in db
$um = new Usermodel();
$um->startTransaction();
$user_id = $um->insert($user_info);
$cm = new Companymodel();
$company_id = $cm->insert($company_info);
//Insert a new user-profile for newly inserted user
$upm = new Userprofilemodel();
$userprofile_info = array(
'user_id' => $user_id,
'company_id' => $company_id
);
$upm->insert($userprofile_info);
$um->endTransaction();
User-model (part of it)
public function startTransaction() {
$this->db->trans_start();
}
public function endTransaction() {
$this->db->trans_complete();
}
public function insert(array $user_info) {
$this->db->insert('user', $user_info);
return $this->db->insert_id();
}
Company-model (part of it)
public function insert(array $company_info) {
$this->db->insert('company', $company_info);
return $this->db->insert_id();
}
Userprofile-model (part of it)
public function insert(array $userprofile_info) {
$this->db->insert('user_profile', $userprofile_info);
return $this->db->insert_id();
}

Categories