I build a custom query and tried use the default paginator, like this:
WodsController.php
$userId = $this->Auth->user('id');
$connection = ConnectionManager::get('default');
$result = $connection->execute("SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods
LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc limit 50")->fetchAll('assoc');
$results = array();
foreach ($result as $r) {
$entity = $this->Wods->newEntity($r);
array_push($results, $entity);
}
$wods = $this->paginate($results);
$this->set('_serialize', ['wods']);
I got this error "Unable to locate an object compatible with paginate".
Now I'm tryng implement custom query paginator, but it's not working.
I implemented paginate and paginateCount functions in the model.
Wods.php file:
public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
$recursive = -1;
$this->useTable = false;
$sql = '';
$sql .= "SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc limit ";
// Adding LIMIT Clause
$sql .= (($page - 1) * $limit) . ', ' . $limit;
$results = $this->query($sql);
return $results;
}
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$sql = '';
$sql .= "SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc";
$this->recursive = $recursive;
$results = $this->query($sql);
return count($results);
}
In the controller WodsController.php
public function index()
{
$this->Wods->recursive = 0;
$this->paginate = array('Wods'=>array('limit'=>10));
$this->set('wods', $this->paginate('Wods'));
}
But the custom paginator is not called, it continues calling the default paginate function. Why ?
Following dragmosh advise (thanks), I investigate CakePHP ORM custom queries builder.
In this solution I used find() function with specific options, after I called the default paginator:
$query = $this->Wods->find()
->select(['Wods.id', 'Wods.titulo','Wods.dia','Wods.rounds','Wods.tempo','Wods.repeticoes','Userwods.user_id'])
->join([
'table' => 'Userwods',
'alias' => 'Userwods',
'type' => 'LEFT',
'conditions' => 'Userwods.wod_id = Wods.id',
])
->where(function ($exp, $q) {
return $exp->isNull('Userwods.user_id');})
->orWhere(['Userwods.user_id' => 4])
->contain(['Userwods'])
->autoFields(true);
$wods = $this->paginate($query);
$this->set(compact('wods'));
$this->set('_serialize', ['wods']);
Related
I have comeup with strange problem in cakephp 3.4. I am running filter query on i18n content like this.
if($this->request->query("q")){
$this->paginate["conditions"][$this->ContractTypes->translationField('title').' LIKE'] = '%'.$this->request->query("q").'%';
}
but following call is ending up in Database error
$records = $this->paginate($this->ContractTypes);
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ContractTypes_title_translation.content' in 'where clause' SELECT (COUNT(*)) AS `count` FROM contract_types ContractTypes WHERE ContractTypes_title_translation.content like :c0
The paginator's count query is not joing i18n table. What is the best approach to solve this problem.
Thanks in advance,
I have solved this by creating my custom paginator component by editing the paginate function. My paginator contains following code incase somebody else is facing the same problem.
namespace Console\Controller\Component;
use Cake\Controller\Component\PaginatorComponent as BasePaginator;
class PaginatorComponent extends BasePaginator
{
public function paginate($object, array $settings = [])
{
$query = null;
if ($object instanceof QueryInterface) {
$query = $object;
$object = $query->repository();
}
$alias = $object->alias();
$options = $this->mergeOptions($alias, $settings);
$options = $this->validateSort($object, $options);
$options = $this->checkLimit($options);
$options += ['page' => 1, 'scope' => null];
$options['page'] = (int)$options['page'] < 1 ? 1 : (int)$options['page'];
list($finder, $options) = $this->_extractFinder($options);
if (empty($query)) {
$query = $object->find($finder, $options);
} else {
$query->applyOptions($options);
}
$cleanQuery = clone $query;
// My Modification Starts Here
$table = $cleanQuery->repository();
$results = $query->all();
$numResults = count($results);
$count = $numResults ? $cleanQuery->select([
"count"=>$cleanQuery
->func()
->count($table->alias().'.'.$table->primaryKey())
])->first()->count : 0;
// My Modification ends Here
$defaults = $this->getDefaults($alias, $settings);
unset($defaults[0]);
$page = $options['page'];
$limit = $options['limit'];
$pageCount = (int)ceil($count / $limit);
$requestedPage = $page;
$page = max(min($page, $pageCount), 1);
$request = $this->_registry->getController()->request;
$order = (array)$options['order'];
$sortDefault = $directionDefault = false;
if (!empty($defaults['order']) && count($defaults['order']) == 1) {
$sortDefault = key($defaults['order']);
$directionDefault = current($defaults['order']);
}
$paging = [
'finder' => $finder,
'page' => $page,
'current' => $numResults,
'count' => $count,
'perPage' => $limit,
'prevPage' => $page > 1,
'nextPage' => $count > ($page * $limit),
'pageCount' => $pageCount,
'sort' => key($order),
'direction' => current($order),
'limit' => $defaults['limit'] != $limit ? $limit : null,
'sortDefault' => $sortDefault,
'directionDefault' => $directionDefault,
'scope' => $options['scope'],
];
if (!$request->getParam('paging')) {
$request->params['paging'] = [];
}
$request->params['paging'] = [$alias => $paging] + (array)$request->getParam('paging');
if ($requestedPage > $page) {
throw new NotFoundException();
}
return $results;
}
}
I am working on a project in Laravel and using DB facade to run raw queries of sql.
In my case I am using DB::select, problem is that pagination method is not working with this DB raw query and showing this error
Call to a member function paginate() on array
I just want how to implement laravel pagination with DB raw queries
here is my code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Notice;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
class NoticeController extends Controller
{
public function index(){
$notices = DB::select('select
notices.id,notices.title,notices.body,notices.created_at,notices.updated_at,
users.name,departments.department_name
FROM notices
INNER JOIN users ON notices.user_id = users.id
INNER JOIN departments on users.dpt_id = departments.id
ORDER BY users.id DESC')->paginate(20);
$result = new Paginator($notices,2,1,[]);
return view('welcome')->with('allNotices', $notices);
}
}
Try:
$notices = DB::table('notices')
->join('users', 'notices.user_id', '=', 'users.id')
->join('departments', 'users.dpt_id', '=', 'departments.id')
->select('notices.id', 'notices.title', 'notices.body', 'notices.created_at', 'notices.updated_at', 'users.name', 'departments.department_name')
->paginate(20);
public function index(Request $request){
$notices = DB::select('select notices.id,notices.title,notices.body,notices.created_at,notices.updated_at,
users.name,departments.department_name
FROM notices
INNER JOIN users ON notices.user_id = users.id
INNER JOIN departments on users.dpt_id = departments.id
ORDER BY users.id DESC');
$notices = $this->arrayPaginator($notices, $request);
return view('welcome')->with('allNotices', $notices);
}
public function arrayPaginator($array, $request)
{
$page = Input::get('page', 1);
$perPage = 10;
$offset = ($page * $perPage) - $perPage;
return new LengthAwarePaginator(array_slice($array, $offset, $perPage, true), count($array), $perPage, $page,
['path' => $request->url(), 'query' => $request->query()]);
}
Don't ever use the pagination logic on php-side!
Use limit and offset on your sql's and leave the rest to the database server.
Additional use a seperate count-select for your statement.
Count:
$sql_count = 'SELECT count(1) cnt FROM ('. $sql . ') x';
$result = \DB::select( DB::raw($sql_count) );
$data['count'] = $result[0]->cnt;
Results:
$sql .= ' LIMIT ' . $offset . ', ' . $limit;
$result = \DB::select( DB::raw($sql) );
$myPaginator = new \Illuminate\Pagination\LengthAwarePaginator($result, $data['count'], $limit, $page, ['path' => action('MyController#index')]);
$data['result'] = $result;
This is suitable for me
$sql = "some sql code";
$page = 1;
$size = 10;
$data = DB::select($sql);
$collect = collect($data);
$paginationData = new LengthAwarePaginator(
$collect->forPage($page, $size),
$collect->count(),
$size,
$page
);
It work for me, see
First use in your controller
use Illuminate\Pagination\Paginator;
then in function
$query = DB::select(DB::raw("SELECT pro.* , (SELECT TIMESTAMPDIFF(DAY,updated_at,'$current_date') from users as u where u.id=pro.id) as days FROM users as pro where role_id = 6 and delete_status=0 and user_status = 'A' and approved_status = 1 and is_clever_courier = 1 having days >= 5"));
$page1 = new Paginator($query, $maxPage);
dd($page1);
o/p =>
Paginator {#1450 ▼
#hasMore: true
#items: Collection {#1509 ▼
#items: array:10 [▼
0 => {#1454 ▶}
1 => {#1455 ▶}
2 => {#1456 ▶}
3 => {#1457 ▶}
4 => {#1458 ▶}
5 => {#1459 ▶}
6 => {#1460 ▶}
7 => {#1461 ▶}
8 => {#1462 ▶}
9 => {#1463 ▶}
]
}
#perPage: 10
#currentPage: 1
#path: "/"
#query: []
#fragment: null
#pageName: "page"
+onEachSide: 3
#options: []
After trying so many things I found the solution and it works fine for me, maybe it will be helpful for someone else.
First, in a PHP class use Illuminate\Pagination\LengthAwarePaginator:
use Illuminate\Pagination\LengthAwarePaginator;
public function index(Request $request) {
$notices = DB::select('SELECT notices.id, notices.title, notices.body, notices.created_at, notices.updated_at, users.name,departments.department_name
FROM notices
INNER JOIN users ON notices.user_id = users.id
INNER JOIN departments on users.dpt_id = departments.id
ORDER BY users.id DESC');
$notices = $this->arrayPaginator($notices, $request);
return view('welcome')->with('allNotices', $notices);
}
public function arrayPaginator($array, $request) {
$page = Input::get('page', 1);
$perPage = 10;
$offset = ($page * $perPage) - $perPage;
return new LengthAwarePaginator(
array_slice(
$array,
$offset,
$perPage,
true
),
count($array),
$perPage,
$page,
['path' => $request->url(), 'query' => $request->query()]
);
}
this work for me ... and good for performance :
query for count all results.
query for main query with offset and limit.
make paginate for current items based on page number.
$sql_count = "select count(*) as aggregate from `products`";
$data_count = DB::select($sql_count);
$count = $data_count[0]->aggregate;
$per_page =10; //define how many items for a page
$pages = ceil($count/$per_page);
$page = ($request->page=="") ?"1" :$request->page;
$start = ($page - 1) * $per_page;
$sql = "select * from `products`";
$sql.= ' LIMIT ' . $start . ', ' . $per_page;
$page = 1;
$size = 10;
$data = DB::select($sql);
$data = $this->paginate($data , $count , $per_page , $request->page);
public function paginate($items, $total , $perPage = 5, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items, $total, $perPage, $page, $options);
}
I'm making a Laravel Pagination based from my query result and be rendered in my view. I'm following this guide http://laravel.com/docs/5.1/pagination but I get an error:
Call to a member function paginate() on a non-object
I'm using query builder so I think that should be ok? Here's my code
public function getDeliveries($date_from, $date_to)
{
$query = "Select order_confirmation.oc_number as oc,
order_confirmation.count as cnt,
order_confirmation.status as stat,
order_confirmation.po_number as pon,
order_summary.date_delivered as dd,
order_summary.delivery_quantity as dq,
order_summary.is_invoiced as iin,
order_summary.filename as fn,
order_summary.invoice_number as inum,
order_summary.oc_idfk as ocidfk,
order_summary.date_invoiced as di
FROM
order_confirmation,order_summary
where order_confirmation.id = order_summary.oc_idfk";
if (isset($date_from)) {
if (!empty($date_from))
{
$query .= " and order_summary.date_delivered >= '".$date_from."'";
}
}
if (isset($date_to)) {
if (!empty($date_to))
{
$query .= " and order_summary.date_delivered <= '".$date_to."'";
}
}
$query.="order by order_confirmation.id ASC";
$data = DB::connection('qds106')->select($query)->paginate(15);
return $data;
}
However when I remove the paginate(15); it works fine.
Thanks
in the doc at this page: http://laravel.com/docs/5.1/pagination
we can see that we are not forced to use eloquent.
$users = DB::table('users')->paginate(15);
but, be sure you don't make a groupBy in your query because, the paginate method uses it.
after i'm no sure you can use paginate with query builder ( select($query) )
--- edit
You can create collection an use the paginator class :
$collection = new Collection($put_your_array_here);
// Paginate
$perPage = 10; // Item per page
$currentPage = Input::get('page') - 1; // url.com/test?page=2
$pagedData = $collection->slice($currentPage * $perPage, $perPage)->all();
$collection= Paginator::make($pagedData, count($collection), $perPage);
and in your view just use $collection->render();
public function getDeliveries($date_from, $date_to)
{
$query="your_query_here";
$deliveries = DB::select($query);
$deliveries = collect($deliveries);
$perPage = 10;
$currentPage = \Input::get('page') ?: 1;
$slice_init = ($currentPage == 1) ? 0 : (($currentPage*$perPage)-$perPage);
$pagedData = $users->slice($slice_init, $perPage)->all();
$deliveries = new LengthAwarePaginator($pagedData, count($deliveries), $perPage, $currentPage);
$deliveries ->setPath('set_your_link_page');
return $deliveries;
}
You set it by using the custom pagination..
$query = "Your Query here";
$page = 1;
$perPage = 5;
$query = DB::select($query);
$currentPage = Input::get('page', 1) - 1;
$pagedData = array_slice($query, $currentPage * $perPage, $perPage);
$query = new Paginator($pagedData, count($query), $perPage);
$query->setPath('Your Url');
$this->data['query'] = $query;
return view('Your_view_file', $this->data, compact('query'));
Here you can specify the path by using the setpath().
In your View
#foreach($query as $rev)
//Contents
#endforeach
<?php echo $Reviews->appends($_REQUEST)->render(); ?>
The appends will append the data.
Thank you.
this is the way i did, it use query builder and get the same result with pagination
$paginateNumber = 20;
$key = $this->removeAccents(strip_tags(trim($request->input('search_key', ''))));
$package_id = (int)$request->input('package_id', 0);
$movieHasTrailer = MovieTrailer::select('movie_id')->where('status','!=','-1')->distinct('movie_id')->get();
$movieIds = array();
foreach ($movieHasTrailer as $index => $value) {
$movieIds[] = $value->movie_id;
}
$keyparams = array();
$packages = Package::select('package_name','id')->get();
$whereClause = [
['movie.status', '!=', '-1'],
['movie_trailers.status', '!=', '-1']
];
if(!empty($key)){
$whereClause[] = ['movie.title', 'like', '%'.$key.'%'];
$keyparams['search_key'] = $key;
}
if($package_id !== 0){
$whereClause[] = ['movie.package_id', '=', $package_id];
$keyparams['package_id'] = $package_id;
}
$movies = DB::table('movie')
->leftJoin('movie_package','movie.package_id','=','movie_package.id')
->leftJoin('movie_trailers','movie.id','=','movie_trailers.movie_id')
->where($whereClause)
->whereIn('movie.id',$movieIds)
->select('movie.*','movie_package.package_name','movie_trailers.movie_id as movie_id',
DB::raw('count(*) as total_trailers, movie_id')
)
->groupBy('movie.id')
->paginate($paginateNumber);
If you need to hydrate, you can do this...
$pages = DB::table('stuff')
->distinct()
->paginate(24, ['stuff.id']);
$stuffs = Stuff::hydrate($pages->items());
return view('stuff.index')->with('stuffs', $stuffs)->with('pages', $pages)
$stuffs will contain your model object, $pages will contain your pagination, probably not the most efficient, but it works.
// import those Class into your Laravel Controller
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Input;
use Illuminate\Database\Eloquent\Collection;
// In your public function
$query = DB::select(DB::raw("SELECT * FROM your_table"));
$collection = new Collection($query);
// Paginate
$perPage = 10; // Item per page
$currentPage = Input::get('page') - 1;
$pagedData = $collection->slice($currentPage * $perPage, $perPage)->all();
$pagination = new Paginator($pagedData, $perPage);
return response()->json([
$pagination
], 200);
I am using a real estate component that has a front-end admin area to view property listings. An additional field was added to a section called custom fields that is named Ref (Reference). In the admin listings I am trying to add an additional search that searches for that reference. There are three tables involved here:
1j0_cddir_jomestate Which holds the property listings information such as title and description.
1j0_cddir_fields which is the custom fields created.
1j0_cddir_content_has_fields and this holds the values of the custom fields
I would need to join 1j0_cddir_content_has_fields "fields_id" with 1j0_cddir_fields "id" and 1j0_cddir_jomestate "id" must join 1j0_cddir_content_has_fields "content_id"
I am struggling to figure out how to add this function to the models/admin_listings.php so that I may add that search input to the admin_listings view.
<?php
protected $text_prefix = 'COM_JOMESTATE';
protected $user;
function __construct()
{
parent::__construct();
$this->user=JFactory::getUser();
$this->planID=$this->getPlanID();
}
protected function getListQuery()
{
// Initialise variables.
$db = $this->getDbo();
$query = $db->getQuery(true);
if ($this->planID->profile=='company'){
$query->select(
$this->getState(
'list.select',
'a.id AS id, a.title AS title, a.date_created, a.featured, a.users_id, a.published, '.
'c.title as category_title,a.date_publish,a.date_publish_down,ag.first_name,ag.last_name'
)
);
}else{
$query->select(
$this->getState(
'list.select',
'a.id AS id, a.title AS title, a.featured, a.date_created, a.users_id, a.published, '.
'c.title as category_title,a.date_publish,a.date_publish_down'
)
);
}
$query->from($db->quoteName('#__cddir_jomestate').' AS a');
$query->select('COUNT(l.id) AS viewHow, SUM(l.view_item) AS viewSum');
$query->join('LEFT', '#__cddir_statistic AS l ON (l.item_id = a.id AND l.extension=\'com_jomestate\')');
// Join over the categories.
$query->join('LEFT', '#__cddir_categories AS c ON c.id = a.categories_id');
$query->join('LEFT', '#__cddir_categories AS e ON e.id = a.categories_address_id');
if ($this->planID->profile=='company'){
$query->join('LEFT', '#__cddir_agent AS ag ON a.users_id = ag.users_id');
$query->join('LEFT', '#__cddir_company AS co ON co.id = ag.company_id');
}
$query->join('LEFT', '#__users AS u ON u.id = a.users_id');
// Filter by published published
$published = $this->getState('filter.published');
if (is_numeric($published)) {
$query->where('a.published = '.(int) $published);
}
// Filter by category.
$categoryId = $this->getState('filter.categories_id');
if (is_numeric($categoryId) && $categoryId!=0) {
$cat_tbl = JTable::getInstance('Category', 'JomcomdevTable');
$cat_tbl->load($categoryId);
$rgt = $cat_tbl->rgt;
$lft = $cat_tbl->lft;
$baselevel = (int) $cat_tbl->level;
$query->where('c.lft >= '.(int) $lft);
$query->where('c.rgt <= '.(int) $rgt);
}
$search = $this->getState('filter.search');
if (!empty($search)) {
if (stripos($search, 'id:') === 0) {
$query->where('a.id = '.(int) substr($search, 3));
} else {
$search = $db->Quote('%'.$db->escape($search, true).'%');
$query->where('(a.title LIKE '.$search.' OR a.alias LIKE '.$search.')');
}
}
if ($this->planID->profile=='company'){
$query->where('(a.users_id ='.(int) $this->user->id.' or co.users_id='.(int) $this->user->id.')');
}
else $query->where('a.users_id ='.(int) $this->user->id);
$sort = $this->getState('list.sort');
switch($sort) {
case 'most_viewed':
$query->order($db->escape('viewSum DESC, a.date_publish DESC'));
break;
case 'alfa':
$query->order($db->escape('a.title, a.date_publish DESC'));
break;
case 'featured':
$query->order($db->escape('a.featured DESC, a.date_publish DESC'));
break;
case 'latest':
default:
$query->order($db->escape('a.date_publish DESC'));
}
$query->group($db->escape('a.id'));
return $query;
}
function getCategories()
{
$cat_array = array(array('v'=>'','t'=>JText::_('COM_JOMESTATE_ADM_ALL')));
$query = "SELECT title, id, level FROM #__cddir_categories WHERE extension='com_jomestate.jomestate' ORDER BY lft";
$data = $this->_getList($query);
foreach ($data as $row):
for ($i=1;$i<$row->level;$i++) $row->title=" ".$row->title;
$temp_array=array('v'=>$row->id,'t'=>$row->title);
array_push($cat_array,$temp_array);
endforeach;
return $cat_array;
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* #since 1.6
*/
protected function populateState($ordering = null, $direction = null)
{
// Initialise variables.
$app = JFactory::getApplication('site');
// Load the parameters.
// $params = $app->getParams();
$params = JComponentHelper::getParams('com_jomestate');
$menu = $app->getMenu();
$this->active = $menu->getActive();
if ($this->active) {
$menuParams = $this->active->params;
$global = $menuParams->get('global_option');
if(!$global) {
$paramsa = $menuParams->toArray();
$paramsb = $params->toArray();
foreach($paramsa AS $key=>$p) $paramsb[$key] = $p;
$newObject = (object) $paramsb;
$newObject->activeItemid = $this->active->id;
$params->loadObject($newObject);
}
}
$this->setState('params', $params);
$limit = $this->getUserStateFromRequest($this->context.'.list.limit', 'jdItemsPerPage', $params->get('listing_per_page'), 'uint');
$this->setState('list.limit', $limit);
$value = $app->getUserStateFromRequest($this->context . '.list.limitstart', 'limitstart', 0);
$limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0);
$this->setState('list.start', $limitstart);
$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search', '', 'string');
$this->setState('filter.search', $search);
$categoryId = $this->getUserStateFromRequest($this->context.'.filter.categories_id', 'filter_category', '', 'string');
$this->setState('filter.categories_id', $categoryId);
$sort = $this->getUserStateFromRequest($this->context.'.list.sort', 'jdItemsSort', 'latest', 'string');
$this->setState('list.sort', $sort);
}
public function getUserStateFromRequest($key, $request, $default = null, $type = 'none', $resetPage = true)
{
$app = JFactory::getApplication();
$old_state = $app->getUserState($key);
$cur_state = (!is_null($old_state)) ? $old_state : $default;
$new_state = JRequest::getVar($request, $old_state, 'default', $type);
if (($cur_state != $new_state) && ($resetPage))
{
JRequest::setVar('limitstart', 0);
}
// Save the new value only if it is set in this request.
if ($new_state !== null)
{
$app->setUserState($key, $new_state);
}
else
{
$new_state = $cur_state;
}
return $new_state;
}
public function getUser()
{
return $this->user;
}
public function getToolbar()
{
$document = JFactory::getDocument();
$document->addStyleSheet('administrator/templates/system/css/system.css');
$document->addStyleSheet('components/com_jomestate/assets/css/backadmin.css');
$controller='admin_listings';
jimport('joomla.html.toolbar');
$bar = new JToolBar( 'toolbar' );
if(Joomla_Version::if3()) {
$bar->appendButton( 'standard', 'new', JText::_('COM_JOMESTATE_ADM_ADD'), $controller.'.add', false );
$bar->appendButton( 'standard', 'publish', JText::_('COM_JOMESTATE_ADM_PUBLISH'), $controller.'.publish', false );
$bar->appendButton( 'standard', 'unpublish', JText::_('COM_JOMESTATE_ADM_UNPUBLISH'), $controller.'.unpublish', false );
$bar->appendButton( 'standard', 'delete', JText::_('COM_JOMESTATE_ADM_DELETE'), $controller.'.delete', false );
} else {
$bar->appendButton( 'Frontend', 'new', JText::_('COM_JOMESTATE_ADM_ADD'), $controller.'.add', false );
$bar->appendButton( 'Frontend', 'publish', JText::_('COM_JOMESTATE_ADM_PUBLISH'), $controller.'.publish', false );
$bar->appendButton( 'Frontend', 'unpublish', JText::_('COM_JOMESTATE_ADM_UNPUBLISH'), $controller.'.unpublish', false );
$bar->appendButton( 'Frontend', 'delete', JText::_('COM_JOMESTATE_ADM_DELETE'), $controller.'.delete', false );
}
return $bar->render();
}
Can someone give me a hint what I am doing wrong?
public function getPaymentSumByTypeAndProject($project_id,$type) {
$type = (int) $type;
$project_id = (int) $project_id;
$rowset = $this->tableGateway->select(array('total_amount' => new Expression('SUM(payment.amount)')))->where(array('type' => $type, 'project_id' => $project_id));
$row = $rowset->toArray();
if (!$row) {
throw new \Exception("Busted :/");
}
return $rowset;
}
I want to make the same query:
SELECT SUM(amount) FROM payment WHERE type='$type' AND project_id ='$project_id';
Edit:
I made small progress, i have figured out how to sum whole column
public function getPaymentSumByTypeAndProject($project_id, $type) {
$type = (int) $type;
$project_id = (int) $project_id;
$resultSet = $this->tableGateway->select(function (Select $select) {
$select->columns(array(new \Zend\Db\Sql\Expression('SUM(amount) as amount')))->where('type="0"');
});
return $resultSet;
Maybe someone could help me to figure out how to add condition: "WHERE type='$type' AND project_id='$project_id'" ?
I know this is an old question, but I came across it and figured I'd throw in my two cents:
public function getPaymentSumByTypeAndProject($project_id, $type) {
// This TableGateway is already setup for the table 'payment'
// So we can skip the ->from('payment')
$sql = $this->tableGateway->getSql();
// We'll follow the regular order of SQL ( SELECT, FROM, WHERE )
// So the query is easier to understand
$select = $sql->select()
// Use an alias as key in the columns array instead of
// in the expression itself
->columns(array('amount' => new \Zend\Db\Sql\Expression('SUM(amount)')))
// Type casting the variables as integer can take place
// here ( it even tells us a little about the table structure )
->where(array('type' => (int)$type, 'project_id' => (int)$project_id));
// Use selectWith as a shortcut to get a resultSet for the above select
return $this->tableGateway->selectWith($select);
}
Also, an adapter can be retrieved from a table gateway like this:
$adapter = $this->tableGateway->getAdapter();
But you don't really need it anymore when you select using the above mentioned method.
Ok now this is working, tell me is this how it;s should be done?
public function getPaymentSumByTypeAndProject($project_id, $type) {
$type = (int) $type;
$project_id = (int) $project_id;
$adapter = $this->tableGateway->adapter;
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('payment');
$select->where(array('type'=>$type,'project_id'=>$project_id));
$select->columns(array(new \Zend\Db\Sql\Expression('SUM(amount) as amount')));
$selectString = $sql->getSqlStringForSqlObject($select);
$resultSet = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
return $resultSet;
}
use This one
$select = $this->getSql()->select()
->columns(array('amount' => new \Zend\Db\Sql\Expression('SUM(amount)')))
->where("type ='$type'")
->where("project_id ='$project_id'");
$resultSet = $this->selectWith($select);
$row = $resultSet->current();
// echo $select->getSqlString();die; //check query use this line
if(!$row){
return False;
}
return $row->amount;
try to make like that instead of (int) $type
intval($type);
and
intval($project_id);
and in your sql
change your variables to
'".$type."'
AND
'".$project_id."'