How to translate this SQL query with propel? - symfony1

i don't know how to translate this query :
SELECT distinct(id_ville) FROM `point_location`
I try to do it, but it doesn't work :
$c = new Criteria();
$c->add(PointLocationPeer::ID_VILLE, Criteria::DISTINCT);
$c->setDistinct();
$this->villes = PointLocationPeer::doSelect($c);

Try something like this:
$c = new Criteria();
$c->addSelectColumn(PointLocationPeer::ID_VILLE);
$c->setDistinct();
$this->villes = PointLocationPeer::doSelect($c);

Related

How to use having() in tableGateway in ZF2

How to use having() clause in ZF2?
There is almost no examples on the web how to prepare correct select object with having.
I have query like:
SELECT root_schema_id as `schema_id`
FROM `standard_specific_root_schemas`
WHERE `vehicle_id` IN (".implode(",",$vehiclesIds).")
GROUP BY `schema_id`, rootSubGroup_id HAVING count(*)=".$noOfVehicles
And I'm trying to run it in ZF2:
public function getVehicleWithinCommonRootSubgroupInSpecific($vehiclesIds)
{
$where = new Where();
$where->in('vehicle_id', $vehiclesIds);
$having = new Having('count(*) = '.count($vehiclesIds));
$rowset = $this->tableGateway->select(function (Select $select) use ($where, $having) {
$select
->where($where)
->having($having);
});
if (!$rowset) {
throw new \Exception("Could not find schemas for group $groupId");
}
return $rowset;
}
Of course that part in ZF2 is not finished yet as I wanted to check if it's working first.
I've tried few ways of providing params to having method but everything generates errors.
Help please, I'm desperate...
I cannot test your query, but can try and reproduce the query you need.
I adjusted the having to use ->expression() instead of a variable via the construct.
I also added the group statement.
To view the query I added a var_dump:
$where = new \Zend\Db\Sql\Where();
$where->in('vehicle_id', $vehiclesIds);
$having = new \Zend\Db\Sql\Having();
$having->expression('count(*) = ?', count($vehiclesIds));
$rowset = $this->tableGateway->select(function (\Zend\Db\Sql\Select $select) use ($where, $having) {
$select
->where($where)
->group(array('schema_id', 'rootSubGroup_id'))
->having($having);
var_dump( $select->getSqlString() );
});
Let me know if this helps.
To circumvent the error mentioned in the comments you would have to do something like below:
$sql = $this->tableGateway->getSql();
$select = $sql->select();
$where = new \Zend\Db\Sql\Where();
$where->in('vehicle_id', $vehiclesIds);
$having = new \Zend\Db\Sql\Having();
$having->expression('count(*) = ?', count($vehiclesIds));
$select
->where($where)
->group(array('schema_id', 'rootSubGroup_id'))
->having($having);
$preparedQuery = $sql->prepareStatementForSqlObject($select);
var_dump( $preparedQuery->getSql() );
However, if I'm right, the tableGateway does this for you so the error should go away once you start using the select to query the database.
Also, you can use the above to do that too, just replace this:
$preparedQuery = $sql->prepareStatementForSqlObject($select);
var_dump( $preparedQuery->getSql() );
With:
$this->tableGateway->selectWith($select);

zf2 select columns from joined tables - how?

I feel like I must me missing something very simple. It's a very simple task, all I want to do is get something like:
SELECT * FROM lookup_items
JOIN lookup ON lookup_items.lookup_id = lookup.id
This returns all the columns for all the joined tables, in regular SQL. Here's my attempt in zf2:
$select = new Select();
$select->from('lookup_items');
$select->join('lookup', 'lookup_items.lookup_id = lookup.id');
The result set only includes the columns in 'lookup_items'. I've tried various ways to get the 'lookup' columns, including:
$select->columns(array('lookup_items.*', 'lookup.*'));
But they all just blow up. Surely there's a way to do this, and it's just so simple I'm missing it completely.
I thought a simple example would be avoid confusion, but here's more code:
class LookupItemsTable extends AbstractTableGateway
{
public function getList($resource)
{
$system_name = str_replace('*', '%', strtoupper($resource));
$joinTable = 'lookup';
$select = new Select();
$select->from($this->table);
$select->join($joinTable, "{$this->table}.lookup_id = {$joinTable}.id");
$where = array();
$where[] = "{$this->table}.enabled is true";
$where[] = "{$joinTable}.enabled is true";
$where[] = "UPPER({$joinTable}.system_name) ilike '{$system_name}'";
$select->where($where);
$sort[] = 'sort_order ASC';
$sort[] = 'value ASC';
$select->order($sort);
$rowset = $this->selectWith($select);
return $rowset;
}
}
Where:
$resource = $this->params()->fromRoute('resource', 'BUSINESS');
And $this->table is 'lookup_items'. Really all I want to do is get columns from both joined tables. I guess there's a zf2 way to just make a straight SQL statement without all the OO falderal, so I could just force it that way. But I'd rather work within the framework as much as possible.
Just change this line
$select->join('lookup', 'lookup_items.lookup_id = lookup.id');
to
$select->join('lookup', 'lookup_items.lookup_id = lookup.id', array('lookupcol1', 'lookupcol2');
Raj answer is the best one but it only works if you don't forget to add these fiels in your LookupItems model.
class LookupItems
{
// Your lookup_items fields here...
...
// And the added lookup fields here, the ones you add in the array
public $lookupcol1;
public $lookupcol2;
And in the exchangeArray method :
public function exchangeArray($data)
{
// .... your fields, and the new ones
$this->lookupcol1 = (! empty($data['lookupcol1'])) ? $data['lookupcol1'] : null;
$this->lookupcol2 = (! empty($data['lookupcol2'])) ? $data['lookupcol2'] : null;
}
I figured it out.
Added this:
$select->columns(array('*'));
And then this near the end:
$sql = new Sql($this->adapter);
$statement = $sql->prepareStatementForSqlObject($select);
$rowset = $statement->execute();
This returns the expected result, with the caveat that now my rows are returned as associative arrays instead of objects.
This is how you can create queries with join in zf2.
$resultSet = $this->select(function (Select $select) {
// omit the table name
//$select->from('foo');
$select->join('users', "users.id foo.createdby", 'firstname', '');
$select->order('id ASC');
// echo $select->getSqlString();// to print your query
});
$entities = array();
foreach ($resultSet as $row) {
$entity = new Entity\Foo();
$entity->setId($row->id)
->setFullname($row->fullname)
->setCaseid($row->caseid)
->setTestimonial($row->testimonial)
->setSortorder($row->sortorder)
->setActive($row->active)
->setCreated($row->created)
->setModified($row->modified)
->setFirstname($row->firstname)
->setCreatedby($row->createdby);
$entities[] = $entity;
}
return $entities;

ZF2 - Select with CONCAT

I'm trying to make a select like this:
SELECT c.*, CONCAT(c.provider_id,'#',c.name") FROM contact AS c
so, I'm writing something like this...
$sql = new Sql($this->adapter);
$query = $sql->select()
->from(array('c' => 'contact'))
->columns(array("CONCAT(c.provider_id,'#',c.name"), false)
but, result is:
SELECT c``CONCAT(c.provider_id,'#',c.name AS
CONCAT(c.provider_id,'#',c.name FROM contact AS c
What am i doing wrong?
Thanks for any help!
When i have to extract some columns from a table and add a Sql function, i usually use this code:
$sql = new Sql($this->adapter);
$query = $sql->select()
->from(array('c' => 'contact'))
->columns(array(
'id', 'name', 'data' => new Expression('CONCAT(c.provider_id,'#',c.name)')
)
);
Expression is an instance of Zend\Db\Sql\Expression, the result is:
SELECT `id`, `name`, CONCAT(c.provider_id,'#',c.name) AS `data` FROM `contact` AS `c`
check out Database Expressions if you need to use MySQL functions or anything else which you don't want to be escaped automatically for you. some examples:
https://github.com/ralphschindler/Zend_Db-Examples
$sql = new Sql($this->adapter);
$query = $sql->select()
->from(array('c' => 'contact'))
->columns(array(
'*', new Expression("CONCAT(c.provider_id,'#',c.name) as data")
))
;

SQL to Criteria using propel

I have this sql:
SELECT link.ID, link.URL, link.ANCHOR, link.HOME, link.CREATED_AT
FROM `link`, `linkcategory`
WHERE link.ID=linkcategory.LINK_ID
GROUP BY linkcategory.LINK_ID
HAVING count(linkcategory.category_id) =(select count(*) from categoria)
And I'm trying to generate the criteria, this is the criteria that doesn't work:
$c = new Criteria();
$c->addJoin(self::ID, LinkcategoryPeer::LINK_ID);
$c->addAsColumn('catCount','(SELECT COUNT(*) FROM CATEGORIA)');
$c->addGroupByColumn(LinkcategoryPeer::LINK_ID);
$having = $c->getNewCriterion(count(LinkcategoryPeer::CATEGORY_ID),$c->getColumnForAs('catCount'));
$c->addHaving($having);
return self::doSelect($c);
The returning sql of this criteria is this one:
SELECT (SELECT COUNT(*) FROM CATEGORIA) AS catCount
FROM `link`, `linkcategory`
WHERE link.ID=linkcategory.LINK_ID
GROUP BY linkcategory.LINK_ID
HAVING 1='(SELECT COUNT(*) FROM CATEGORIA)'
I really don't know why the criteria convert the sql incorrectly. Anyone knows where is the mistake?
Try with this query. I don't remember how to perform a link.* using Propel. But I think the problem with having is that you are using the PHP count function insteand of the MySQL one.
$c = new Criteria();
$c->addSelectColumn(self::ID);
$c->addSelectColumn(self::URL);
$c->addSelectColumn(self::ANCHOR);
$c->addSelectColumn(self::HOME);
$c->addSelectColumn(self::CREATED_AT );
$c->addJoin(self::ID, LinkcategoryPeer::LINK_ID);
$c->addGroupByColumn(LinkcategoryPeer::LINK_ID);
$having = $c->getNewCriterion(
'COUNT('.LinkcategoryPeer::CATEGORY_ID.')'),
$c->getColumnForAs('catCount')
);
$c->addHaving($having);
return self::doSelect($c);

how to translate this query into Criteria?

I try to translate this query into Criteria (with Propel), but without success.
Can you help me please ?
SELECT DISTINCT (email)
FROM user, travail
WHERE travail.id_user = user.id_user
AND id_site = "1"
AND `droits` = "1"
This my Criteria query :
$c = new Criteria();
$c->add(self::DROITS, 1, Criteria::EQUAL);
$c->add(TravailPeer::ID_SITE, 1, CRITERIA::EQUAL);
$c->setDistinct(self::EMAIL);
How about this:
$c = new Criteria();
$c->add(UserPeer::DROITS, 1);
$c->addJoin(UserPeer::ID_USER, TravailPeer::ID_USER);
$c->add(TravailPeer::ID_SITE, 1);
$c->clearSelectColumns();
$c->addSelectColumn(UserPeer::EMAIL);
$c->setDistinct();
$rs = UserPeer::doSelectRS($c);
Hi You can use propel builder to translate not only this but any sql to the criteria. following is one of the online builder site.
http://propel.jondh.me.uk/

Resources