query to select from two tables on symfony - php

I am learning symfony framework. Now I am getting all data from mysql table orders this way:
$c = new Criteria();
$this->items = OrdersPeer::doSelect($c);
Also I have other table orders_complete. How can I get data from tables orders and orders_complete?
I want to do this query:
SELECT * FROM orders, orders_complete WHERE orders.id =
orders_complete.id

If I remember right, with propel you should be able to do something like :
$c = new Criteria();
$orders = OrdersPeer::doSelect($c);
foreach($orders as $order) {
$complete = $order->getOrderCompletes();
// do something with $order and $complete ...
}
This providing that you have defined the two tables relationship within your schema file...
Do check the propel documentation regarding this : http://propelorm.org/documentation/04-relationships.html#using-relationships-in-a-query

Related

Laravel query builder add complex query result

I have three models with the following hierarchy :
User
id
....some other properties
Journey
id
user_id
budget
....some other properties
Confirmation
id
journey_id
user_id
....some other properties
I have a HasMany from User to Journey, a HasMany from Journey to Confirmation.
I want to get the sum for a column of the journeys table by going through the confirmations table but I cannot create an intermediate HasManyThrough relation between User and Journey by using Confirmation.
I have tried to do
public function journeysMade(): HasManyThrough
{
return $this->hasManyThrough(Journey::class, Confirmation::class);
}
// And after,
User::with(...)->withSum('journeysMade','budget')
But it was not possible because the relations are not adapted.
With hindsight, the sql query I want to translate would look like
select coalesce(sum(journeys.budget), 0) as income
from journeys
inner join confirmations c on journeys.id = c.journey_id
where c.user_id = ? and c.status = 'finalized';
How can I implement this query considering how I will use my query builder :
$driversQueryBuilder = User::with(['profile', 'addresses']); // Here
$pageSize = $request->input('pageSize', self::DEFAULT_PAGE_SIZE);
$pageNumber = $request->input('pageNumber', self::DEFAULT_PAGE_NUMBER);
$driversPaginator = (new UserFilterService($driversQueryBuilder))
->withStatus(Profile::STATUS_DRIVER)
->withCountry($request->input('country'))
->withSex($request->input('sex'))
->withActive($request->has('active') ? $request->boolean('active') : null)
->get()
->paginate(perPage: $pageSize, page: $pageNumber);
return response()->json(['data' => $driversPaginator]);
The reason why I want to get a builder is because UserFilterService expects a Illuminate\Database\Eloquent\Builder.
Do you have any idea about how I can solve this problem ?
Not 100% sure what exactly you want to sum, but I think you need the following query
$user->whereHas('journeys', function($query) {
$query->whereHas('confirmations', function($subQuery) {
$subQuery->sum('budget);
}
});
If you the above query isn't summing the budget you need, you just add another layer of abstraction with whereHas methods to get exactly what you need. Hope this helps!
EDIT:
$user->whereHas('confirmations', function($q) {
$q->withSum('journeys', 'budget')->journeys_sum_budget;
}

Symfony query ids from ManyToMany relation table for every entity item

I have two entities Article and Tag with a Many to Many relation. For a bulk edit I query some attributes from every Articles. In that query I also want to query all assigned Tag-IDs from every Article.
I read something about the function GROUP_CONCAT() but Doctrine doesn't support that function yet.
My Doctrine statement is currently like that:
$this->getEntityManager()->createQuery('SELECT e.articleId, e.articleTitle, t.tagId FROM App\Entity\Article e LEFT JOIN e.tags t');
It would be best to fetch those assigned Tag-IDs as an array.
So I extended Doctrine with GROUP_CONCAT function from github.com/beberlei/DoctrineExtensions and use following code to get all IDs as an array:
$query = $this->getEntityManager()->createQuery('SELECT e.articleId, e.articleTitle, GROUP_CONCAT(t.tagId) AS tagIds FROM App\Entity\Article e LEFT JOIN e.tags t GROUP BY e.articleId');
$articleArray = $query->execute();
for ($i = 0; $i < count($articleArray); $i++) {
if (strpos($articleArray[$i]['tagIds'], ',')) {
$arr = array_map('intval', explode(',', $articleArray[$i]['tagIds']));
$articleArray[$i]['tagIds'] = ($arr) ? $arr : [];
}
elseif (!is_null($articleArray[$i]['tagIds'])) $articleArray[$i]['tagIds'] = [(int) $articleArray[$i]['tagIds']];
else continue;
}

Getting data from 2 tables in magento

I created 2 textension in magento along with 2 different tables. First extension store data in table-1 while second second extension store data in table-2. Now i want to display data in first extension by LeftJoin. It show data without leftjoin from first table but not showing data with leftjoin from both the tables.
This code in block.php
public function methodblock()
{
$collection = Mage::getModel('test/test')->getCollection();
$returnCollection = $collection->getSelect()
->joinLeft('magento_answer', 'id_pfay_test=question_id',
array('*'), null , 'left');
return $returnCollection;
}
On Layout side. dislplaydata.phtml
<?php
$collection = $this->testmethodblock();
foreach($collection as $rows {
echo $rows ->getData('name');
}
I Got the answer. I use the custom query which works for me.
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$qTable = $resource->getTableName('pfay_test');
$aTable = $resource->getTableName('answer/answer');
$query = 'SELECT * FROM '.$qTable.' q left join '.$aTable.' a ON a.question_id=q.id_pfay_test';
$results = $readConnection->fetchAll($query);
return $results;

Symfony2 Doctrine, How to fetch only the column names of particular table

Hi i want only the table field names(column names) how to achieve that, as of now i do have the following code -
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('SkerpInventoryBundle:InventoryMaster')->findAllIndex();
I am using the repositories to fetch all the data of the table. Now in "$entities" I am having the result data. Can anyone let me know how to fetch only the field name.
I guess, this is what you need (assume that you are in your controller):
$mappings = $this->getDoctrine()->getManager()->getClassMetadata('AcmeBundle:SomeEntity');
$fieldNames = $mappings->getFieldNames();
You can use DQL (Doctrine Query Language) For this. For example:
$query = $em->createQuery('SELECT u.username FROM CmsUser u');
$users = $query->getResults(); // array of CmsUser username values
echo $users[0]['username'];
For more information on DQL see:
http://docs.doctrine-project.org/en/2.1/reference/dql-doctrine-query-language.html

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;
}

Categories