Where is the result of sum? - php

I want to sum a field tiempo_acumulado for each tarea_id. I try this but dont work, is wrong or how can do this.
foreach ($idstareas as $idtarea)
{
$sumatorio = $this->ProyectosCategoriasTareas->find();
$sumatorio
->select(['suma' => $sumatorio->func()->sum('tiempo_acumulado')])
->where(['tarea_id'=>$idtarea->id])
->toArray();
debug($sumatorio);
die();
}
I dont find suma or the result

This work! for me
foreach ($idstareas as $idtarea)
{
$arrayTareas = $this->ProyectosCategoriasTareas->find('all')->where(['tarea_id'=>$idtarea->id]);
$collection = new Collection($arrayTareas);
$sumDeHoras = $collection->sumOf('tiempo_acumulado');
debug($sumDeHoras);
die();
}

Related

Getting Message: Invalid argument supplied for foreach() when there is no records in the table

I have two tables with records. In the first table, I am displaying personal information and in the second table, I am adding the activities details.
Now I am trying to display the record using joins. So below code, I am using in the model
public function getMemberActivity($gotMemberId){
$getDetails = array('members.member_id'=>$gotMemberId,'member_activity.activity_status'=>1,'members.is_Approved'=>1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id','LEFT')
->get()
->result();
//echo $this->db->last_query();
//print_r($result);
if($result)
{
return $result;
}
else
{
return 0;
}
}
Controller
Note: I am getting multiple member id here because I have above some more logic. that's the reason I am using for each.
$ActivityData=[];
foreach ($data['getAllMember'] as $key => $m_id) {
$ActivityData[] = $this->Access_model->getMemberActivity($m_id->member_id);
}
$data['MemberActivity'] = $ActivityData;
Now If I found the records related the member id in the secondary table then I am getting the output but if not found a record in the second table then I am getting the error Message: Invalid argument supplied for foreach()
If I remove 'member_activity.activity_status'=>1 from the where clause then my join query is working. I mean I am getting the member records.
->join('member_activity', 'members.member_id = member_activity.member_id','LEFT')
View
$SActivity=$MemberActivity;
//print_r($SActivity);
if($SActivity){
foreach ($SActivity as $sec_1) {
foreach ($sec_1 as $sec_activities) {
//list here
}
}
}
else{echo"no data availalbe";}
So my expected output is, I have to display the records if found in the second table if not found then also display the member table records.
Would you help me out in this?
Move your where condition 'member_activity.activity_status'=>1 in JOIN as below,
$public function getMemberActivity($gotMemberId){
$getDetails = array('members.member_id'=>$gotMemberId,'members.is_Approved'=>1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id AND member_activity.activity_status = 1','LEFT')
->get()
->result();
//echo $this->db->last_query();
//print_r($result);
if($result)
{
return $result;
}
else
{
return 0;
}
}
Hope this will be help you.
Final query like this:
SELECT members.*,member_activity.* FROM members LEFT JOIN member_activity ON members.member_id = member_activity.member_id AND member_activity.activity_status = 1
WHERE 'members.member_id' = $gotMemberId AND 'members.is_Approved' = 1;
The problem is with your model function getMemberActivity. If there is no record then you returns 0 and when you foreach you will get error because its not an array. So you can simply return $result since codeigniter return default array.
public function getMemberActivity($gotMemberId)
{
$getDetails = array('members.member_id' => $gotMemberId, 'members.is_Approved' => 1);
$result = $this->db->where($getDetails)
->from('members')
->join('member_activity', 'members.member_id = member_activity.member_id AND member_activity.activity_status = 1', 'LEFT')
->get()
->result();
return $result;
}
Second option is you can check !empty before your foreach.
I hope this will help you, try
foreach ($SActivity as $sec_1) {
if (!empty($sec_1)):
foreach ($sec_1 as $sec_activities) {
//list here
print_r($sec_activities);
}
endif;
}

Codeigniter group_by not working properly

Im trying get a list of userIds from the videos table. This table contains the media files that get uploaded the users. This is my code
$this->db->select("videos.user_id as userId");
$this->db->limit('10', $document['offset']);
$this->db->group_by('userId');
$this->db->order_by('id','desc');
$recentUploads = $this->db->get('videos')->result_array();
if (!empty($recentUploads))
{
foreach ($recentUploads as $record)
{
$totalPostMedia = $obj->totalPostMedia($record);
$record['totalPostMedia'] = $totalPostMedia;
$resData = $this->db->select("username, profileImage")->from('users')->where('id', $record['userId'])->get()->row_array();
$record['uploadBy'] = $resData['username'];
$record['profileImage'] = "http:...com/profileImage/".$resData['profileImage'];
$Mydata[] = $record;
}
}
The result get is missing some of the userIds from the table. I have tried $this->db->distinct() as well. Still got the same result. The only way i get a result with no duplicates is when i remove $this->db->order_by('id','desc'); or make it asc instead of desc. But i want to get the latest records from the table. how do i do this? Am i doing something wrong? any help would be much appreciated.
try this
$this->db->select("videos.user_id as userId");
$this->db->from("videos");
$this->db->group_by('userId');
$this->db->order_by('id','desc');
$this->db->limit('10', $document['offset']);
$recentUploads = $this->db->get()->result_array();
if (count($recentUploads)>0)
{
foreach ($recentUploads as $record)
{
$totalPostMedia = $obj->totalPostMedia($record);
$record['totalPostMedia'] = $totalPostMedia;
$resData = $this->db->select("username, profileImage")->from('users')->where('id', $record['userId'])->get()->row_array();
$record['uploadBy'] = $resData['username'];
$record['profileImage'] = "http:...com/profileImage/".$resData['profileImage'];
$Mydata[] = $record;
}
}
in your request (i mean select videos.user_id as userId) in the group_by ligne you make userId to do the group by traitement. your userId alias is not knowing as colum name that can do any traitement of it.
for that replace your userId by videos.user_id in your group by ligne.
your code will be like this to work for you
$this->db->select("videos.user_id as userId");
$this->db->limit('10', $document['offset']);
$this->db->group_by('videos.user_id');
$this->db->order_by('id','desc');
$recentUploads = $this->db->get('videos')->result_array();
if (!empty($recentUploads))
{
foreach ($recentUploads as $record)
{
$totalPostMedia = $obj->totalPostMedia($record);
$record['totalPostMedia'] = $totalPostMedia;
$resData = $this->db->select("username, profileImage")->from('users')->where('id', $record['userId'])->get()->row_array();
$record['uploadBy'] = $resData['username'];
$record['profileImage'] = "http:...com/profileImage/".$resData['profileImage'];
$Mydata[] = $record;
}
}
use max(id)
as in $this->db->select("videos.user_id as userId,max(id)");`
so you might try:
$this->db->select("videos.user_id as userId, max(id)");
$this->db->limit('10', $document['offset']);
$this->db->group_by('userId');
$this->db->order_by('id','desc');
$recentUploads = $this->db->get('videos')->result_array();
if (!empty($recentUploads))
{
foreach ($recentUploads as $record)
{
$totalPostMedia = $obj->totalPostMedia($record);
$record['totalPostMedia'] = $totalPostMedia;
$resData = $this->db->select("username, profileImage")->from('users')->where('id', $record['userId'])->get()->row_array();
$record['uploadBy'] = $resData['username'];
$record['profileImage'] = "http:...com/profileImage/".$resData['profileImage'];
$Mydata[] = $record;
}
}
https://stackoverflow.com/a/14770936/1815624

PHP bringing back all rows instead of requested

I have a query that is bringing back all rows from the table instead of the fields I have specified. Can you see any mistakes in this? I'm using codeigniter.
Thanks in advance!
unset($conditions);
$conditions['conditions'] = array("accountid"=>$this->sessionInfo['database_account_id'],
"DATE_FORMAT(salestart,'%Y-%m-%d')"=>$today,
"shop"=>"london"
);
$conditions['group_by'] = "item";
$conditions['fields'] = "accountid, item, count(uniqueid) as totalitems, sum(options) as totaloptions, colour";
$today_sales = $this->Database_Model->selectData("sales",$conditions);
My model is:
public function selectData($table,$condition=array()) {
if(isset($condition['fields'])){
$fields = $condition['fields'];
}
else{
$fields = "*";
}
$this->Database->select('*');
$this->Database->from($table);
if(isset($condition['conditions'])){
$this->Database->where($condition['conditions']);
}
if(isset($condition['group_by'])){
$this->Database->group_by($condition['group_by']);
}
if(isset($condition['order_by'])){
$this->Database->order_by($condition['order_by']);
}
if(isset($condition['where_in'])){
$where_in = $condition['where_in'];
foreach($where_in as $key =>$value){
$this->Database->where_in($key,$value);
}
}
if(isset($condition['joins'])){
$joins = $condition['joins'];
foreach($joins as $join){
$this->Database->join($join['table'], $join['joinWith'],$join['type']);
}
}
$query = $this->Database->get();
return $query->result_array();
}
Change this
$this->Database->select('*');
to this
$this->Database->select($fields);

Solr Search sort by score in solr1.2

One of my project use solr1.2 and when i use "sort by score" in search function it's not working.I don't know why?
Can any one explain this.I am totally confuse.
my controller where i do :
protected function globalSearch($searchTerm, $productFilter = array())
{
$solrService = $this->get('syd.solr_service');
$solrQuery = new SolrQuery('*:*');
$solrQuery->addField('id')
->addField('first_product_slug')
->addField('first_product_name')
->addField('name')
->addField('slug')
->addField('thumbnail_path')
->addField('product_slug')
->addField('design_category_id')
->addSortField('score', SolrQuery::ORDER_DESC);
$solrQuery->set("group", "true");
$solrQuery->set("group.field", "first_product_id");
$solrQuery->set("group.limit", 4);
if($searchTerm){
$filterQueries = array();
$searchTerms = explode(' ',$searchTerm);
$searchTerms[] = $searchTerm;
$searchTerm = '("' . implode('" OR "', $searchTerms) . '")';
$filterQuery = sprintf(self::SEARCH_STRING, $searchTerm);
$solrQuery->addFilterQuery($filterQuery);
}
if (!empty($productFilter))
{
$productFiltersArr = array();
$productFilterQry = '';
foreach ($productFilter as $productFilterValue )
{
$productFiltersArr[] = 'first_product_slug:' . $productFilterValue;
}
$productFilterQry = implode(' OR ', $productFiltersArr);
$solrQuery->addFilterQuery($productFilterQry);
}
$solrQuery->setRows(1000);
try {
$solrObject = $solrService->query(
'SydPrintBundle:DesignTemplate',
$solrQuery,
SolrService::WRITER_FORMAT_SOLR_OBJECT
);
$templates = $solrObject->offsetGet('grouped')->offsetGet('first_product_id')->offsetGet('groups');
}
catch (\Exception $e) {
$templates = array();
}
if (!$templates) {
if (!empty($searchTerm)) {
$this->setFlash('catalog-message', 'No results found for your search.');
}
return array();
}
if (!$searchTerm) {
if (!empty($searchTerm)) {
$this->setFlash('catalog-message', 'No results found for your search.');
}
return array();
}
return $templates;
}
When you say when i use "sort by score" in search function it's not working I assume you are telling that the results are not sorted by score.
This is because your main query is *:* and you are adding your search terms via a filter query, which won't influence the score. See https://wiki.apache.org/solr/CommonQueryParameters#fq where it says
This parameter can be used to specify a query that can be used to restrict the super set of documents that can be returned, without influencing score.
So if you make the search term filter query as your main query, then you should see results sorted by score.
Update:
Instead of
$solrQuery = new SolrQuery('*:*');
use
$solrQuery = new SolrQuery();
and instead of
$solrQuery->addFilterQuery($filterQuery);
use
$solrQuery->setQuery($filterQuery);

How to correlate below given foreach loop?

I have two for loops given below
foreach($result_access as $acc){
$usr_access_id[] = $acc->id;
$usraccess[] = $acc->rules;
}
> UPDATED
foreach($somearray as $someid){//Updated
foreach($usraccess as $accessusr){
if(in_array($someid,$usraccess)){
$myid = ??;///Here i want the $usraccess associated $acc->id, how can I get that?
}
}
}
As you can see that I want the $myid get assigned with $acc->id which should be associated with the current $usraccess array
Here's a sane solution:
foreach ($result_access as $acc) {
if (in_array($someid, $acc->rules)) {
$myid = $acc->id;
}
}
The insane solution would be:
...
foreach($usraccess as $i => $accessusr){
if(in_array($someid,$usraccess)){
$myid = $usr_access_id[$i];
}
}
Is this what you want?
foreach($result_access as $acc){
$usr_access_id[] = $acc->id;
$usraccess[ $acc->id ] = $acc->rules;
}
foreach($usraccess as $accessusr){
if(in_array($someid,$usraccess)){
$myid = $usraccess[ $someid ] ;///Here i want the $usraccess associated $acc->id, how can I get that?
}
}

Categories