try to perform a query with join with Zend (SE) - php

I have 4 tables on my DB;
merchants, pay_method, spendings ans transaction_type.
They all have an id and a title, except spend (spend have the Foreign keys of the others and other field like user_id, comment, ... ).
I try to have all the informations of all the tables for an unique user_id!
for perform it, I tried a little test that doesn't run :
public function getSpendingsForUser( $userid )
{
$mercTable = Engine_Api::_()->getDbTable('merchants', 'spendings');
$mercName = $mercTable->info('name');
$table = Engine_Api::_()->getDbTable('spendings', 'spendings');
$spendName = $table->info('name');
$select = $table->fetchAll(
$table->select()
->joinLeft($mercName, "$mercName.merchant_id = $spendName.merchant_id", NULL)
->where('user_id = ?', $userid)
->group('spending_id')
);
return $select;
}
An in the view file :
foreach($this->spendings as $s) {
var_dump($s->comment);
}
How can I make the join correctly to have all the info from the user_id ???
Thanks a lot !!!

You should define doesn't run to help us help you. But I can tell you you probably need to ->setIntegrityCheck(false);
$select = $table->fetchAll(
$table->select()
->setIntegrityCheck(false);
->joinLeft($mercName, "$mercName.merchant_id = $spendName.merchant_id", NULL)
->where('user_id = ?', $userid)
->group('spending_id')
);
Before the join.

Related

Codeigniter where not exists does not work

I'm working on Codeigniter project and came across a problem. I would like that my function on my model to bring me the data from the POST table, where POST_ID in CATEGORY Table is not null, without joining the table, so (do not bring back the data whose POST_ID in CATEGORY table not exists).
so i tried this method how can i get this result?
code: // MyModel
function get_data() {
$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
if ($id != null) {
$this->db->where('ID',$id);
$result = $this->db->select('POST.ID,POST.DATE,'
. ' TYPE.Post_Type P_TYPE,)
->join('TYPE', 'POST.TYPE_ID = TYPE.ID', 'left')
->order_by('POST.ID', 'DESC')
->where_in('POST.Post_Type = type_1, type_2')
->where("NOT EXISTS(SELECT POST_ID FROM CATEGORY WHERE POST.ID=CATEGORY.POST_ID )", FALSE)
->get('POST');
}
return $result;
}
Thank you for help
It would be better to use IN if you are trying to have a data where is not null ( meaning it exists ) or you can also change it to NOT IN if the answer you are looking for is the other way around. anyway, i did not change anything in your query, i just put the POST_ID and IN in the where statement
function get_data() {
$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
if ($id != null) {
$in = array('type_1', 'type_2');
$this->db->where('ID',$id);
$this->db->select('POST.ID,POST.DATE,TYPE.Post_Type as P_TYPE', FALSE);
$this->db->join('TYPE', 'POST.TYPE_ID = TYPE.ID', 'left');
$this->db->order_by('POST.ID', 'DESC');
$this->db->where_in('POST.Post_Type', $in);
$this->db->where("POST.POST_ID IN(SELECT C.POST_ID FROM CATEGORY C )");
$this->db->from('POST');
$result = $this->db->get();
}
return $result;
}

Doctrine ORM - How to choose the first selected item in select query

I'm using Symfony 4 with EasyAdmin and I need to make a select query that retrieve all the users, but I want the connected user to be selected as the first result.
I don't know how to proceed at all. I was thinking maybe do multiple select in the same query ? but I don't even know how to do this.
So far I have this :
$repo = $this->getDoctrine()->getRepository(User::class);
$authUser = $this->getUser();
$queryBuilder = $repo->createQueryBuilder('u');
return $queryBuilder;
// Doctrine createQueryBuilder looks like this
public function createQueryBuilder($alias, $indexBy = null)
{
return $this->_em->createQueryBuilder()->select($alias)->from($this->_entityName, $alias, $indexBy);
}
EDIT : I imperatively need to return the queryBuilder object, not the result set, that's why it's tricky.
An approach that will query all users, but gives you an array in the order you describe:
$users = $userRepository->findall();
foreach ($users as $user) {
$this->getUser() == $user ? $currentUser[] = $user : $otherUsers[] = $user;
}
$myUserList = array_merge($currentUser, $otherUsers);
Two sidenotes: 1: This queries all users and then splits them. I'm not sure if this could be what you want. 2: if no user is currently logged in this code will not work because $currentUser won't be defined. Of course, you can change it so it will also work when no user is logged in.
Edit based on the fact that returning the querybuilder is imperative:
You can use CASE to test and create a property, which you can hide with AS HIDDEN in your query and then order by this hidden property like so:
public function currentUserFirst($userId){
$qb = $this->createQueryBuilder('u')
->select('u, CASE WHEN u.id = :userId THEN 0 ELSE 1 END AS HIDDEN order')
->setParameter('userId', $userId)
->orderBy('order', 'ASC');
return $qb;
}
As the first comment pointed out, you will need to use a UNION, which is not supported in DQL.
Therefore your only option is to use a native query using the Connection which you need to get from the EntityManager.
It would look something like this:
$id = $this->getUser()->getId();
$sql = 'SELECT * FROM `users` WHERE `id` = :id UNION SELECT * FROM `users` WHERE`id` != :id'
$users = $this->getDoctrine()->getConnection()->fetchAll($sql, compact('id'));
You can use setMaxResults:
$qb->andWhere('q.start <= :start')
->setParameter(':start', $value)
->setMaxResults(1)
;

Codeigniter Many to Many Error

I have 3 tables ...
instructors, classes and instructor_teach
I want to display a list of classes that the instructor teaches
I have been using tutorials and the like to try and work this out so if my code is messy i do apologize.
Model...
function getMemberPrograms($id){
$this->db->select('*');
$this->db->from('instructor_teach');
$this->db->join('instructor_teach', 'instructors.id = instructor_teach.instructor_id');
$this->db->join('classes', 'instructor_teach.program_id = classes.id');
$this->db->where('instructor_teach.instructors_id', $id);
return;
}
In the controller i just have a print_r statement to see what the results are but at the moment i am getting
Error Number: 1066
Table/alias: 'instructor_teach' non unique
SELECT * FROM (`instructor_teach`, `classes`) JOIN `instructor_teach`
ON `instructors`.`id` = `instructor_teach`.`instructor_id` JOIN
`classes` ON `instructor_teach`.`program_id` = `classes`.`id` WHERE
`instructor_teach`.`instructors_id` = '1'
Filename: C:/wamp/www/fitness/application/models/members_model.php
Line Number: 16
what i want is an array that has all the information from the classes the instructor teaches so
instructor 1 teaches class 1, class 2
array would return
class 1.name
class 1.description
class 2.name
class 2.description
etc..
I hope this makes sense as i am still getting to terms with this
Many Thanks
Joe
I think you are joining the table instructor_teach to it self instructor_teach
take a look:
$this->db->from('instructor_teach');
$this->db->join('instructor_teach', 'instructors.id = instructor_teach.instructor_id');
I think it should be:
$this->db->from('instructor_teach');
$this->db->join('instructors', 'instructors.id = instructor_teach.instructor_id');
:)
$this->db->select('*');
$this->db->from('instructor_teach');
$this->db->join('instructor_teach', 'instructors.id = instructor_teach.instructor_id');
$this->db->join('classes', 'instructor_teach.program_id = classes.id');
$this->db->where('instructor_teach.instructors_id', $id);
First is you select to table instructor_teach then afterwards you want to join it again with table instructor_teach where in it will give you a error.
And one thing also if you can select only important columns from each tables is much more okay.
I think the query should look like this
$this->db->select('*');
$this->db->from('instructors');
$this->db->join('instructor_teach', 'instructors.id = instructor_teach.instructor_id');
$this->db->join('classes', 'instructor_teach.program_id = classes.id');
$this->db->where('instructor_teach.instructors_id', $id);
i don't know if this correct, but try to change the first join with instructor table
$this->db->join('instructor_teach', 'instructors.id = instructor_teach.instructor_id');
to
$this->db->join('instructor', 'instructors.id = instructor_teach.instructor_id');
try this
function getMemberPrograms($id){
$this->db->select('*');
$this->db->from('instructor_teach');
$this->db->join('instructor', 'instructors.id = instructor_teach.instructor_id');
$this->db->join('classes', 'instructor_teach.program_id = classes.id');
$this->db->where('instructor_teach.instructors_id', $id);
return true;
}

ZF2 multiple tables join in one model, get columns from join table

So here is my query:
public function fetchAd($adID){
$row = $this->tableGateway->select(function(Select $select) use ($adID){
$select->join('adDetails','adDetails.adID = ads.adID',array('*'),'inner');
$select->where(array('ads.adID' => $adID));
});
return $row->current();
}
So what I'm doing I'm querying the ad table and join the adDetails table in order for me to get the details for a certain AD, the problem is that the entity AD which belongs to the model that I'm doing the query, it doesn't have the columns names(variables) from the adDetails table; so it will only return the columns from the AD table, because the entity doesn't have those fields in the exchangeArray()
I have tried to extend the AD entity to use the AdDetails entity but it returns now to object array but with the fields as null, because it can;t populate them.
So, how should I do this, in order for me to have all the columns available in the model for the tables that will join?
I'm planning to join other tables as well.
Ok I solved the problem, the thing is that it will return an array, and it won't use the ORM style, but it does the job, for now relations are not supported in ZF2 like in ZF1;
use Zend\Db\Sql\Sql,
Zend\Db\Sql\Where;
$sql = new Sql($this->tableGateway->getAdapter());
$select = $sql->select();
$select->from($this->tableGateway->table)
->join('adDetails','adDetails.adID = ads.adID',array('*'),'inner');
$where = new Where();
$where->equalTo('ads.adID', $adID) ;
$select->where($where);
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
return $result->current();
public function fetchJoin()
{
$select = new \Zend\Db\Sql\Select;
$select->from('tablea a');
$select->columns(array('*'));
$select->join('tableb b', "b.id = a.b_id", array('field1'), 'left');
// to display query string remove comment in next line
//echo $select->getSqlString();
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}

Zend framework leftJoin

Here is the code that doesn't work.
$select = $tariffsTable->select(Zend_Db_Table_Abstract::SELECT_WITHOUT_FROM_PART)
->from('tariff', null)
->where('id = ?', $this->id)
->joinLeft('characteristic_value',
'characteristic_value.tariff_id = id',
array('value_' . $locale, 'characteristic_id'))
->joinLeft('characteristic',
'id = characteristic_value.characteristic_id',
array('name_' . $locale, 'alias'));
$select->setIntegrityCheck(false);
$tariffCharacteristics = $tariffsTable->fetchAll($select)->toArray();
Thank you for help! I have solved the problem. Here is working code:
$select = $tariffsTable->select(Zend_Db_Table_Abstract::SELECT_WITHOUT_FROM_PART)
->from('tariff', null)
->joinLeft( array('characteristic_value'),
'characteristic_value.tariff_id = tariff.id',
array('value_' . $locale))
->joinLeft(array('characteristic'),
'characteristic.id = characteristic_value.characteristic_id',
array('name_' . $locale, 'alias'))
->where('tariff.id = ?', $this->id);
$select->setIntegrityCheck(false);
It is because your are using id column on WHERE and/or LEFT JOIN ON clause while an id column should be present in both table your are trying to join.
You need to specify which id should be used in both case.
Like characteristic.id or characteristic_value.id or tarriff.id.
You can use alias by using array as a parameter for from() and joinLeft() methods.
$select->from(array('t' => 'tarriff'))
->where('t.id = ?', $this->id);

Categories