cakephp3 select count(*) from other models - mysql

I have 3 models Employees Customers and Partners
I want to display the count of all the tables employees customers and partners in dashboard view of Employees model.
EmployeesController.php
<?php
namespace App\Controller;
class EmployeesController extends AppController
{
public function dashboard()
{
}
}
?>
I'm new to cakephp and I have no idea how to query other model tables at all.
Please point me to good tutorial or documentation for this. It will be helpful

I fixed it using the following codes.
// Controller
$this->loadModel("Customer");
$query = $this->Customers->find('all', [
'conditions' => ['Customers.area_cd =' => $this->Auth->user('area_cd')]
]);
$entity_count[0] = $query->count();
$this->loadModel("Employee");
$query = $this->Employees->find('all', [
'conditions' => ['Employees.area_cd =' => $this->Auth->user('area_cd')]
]);
$entity_count[1] = $query->count();
$this->loadModel("Partner");
$query = $this->Partners->find('all', [
'conditions' => ['Partners.area_cd =' => $this->Auth->user('area_cd')]
]);
$entity_count[2] = $query->count();
$this->set(compact('entity_count'));
// View
<?= $entity_count[0] ?>

The query to use would be a nested query, assigned to an array. Then you can access the values from there.
In particular, you would want to write something like:
$result = List();
$result->query('SELECT COUNT(SELECT * FROM usertable), COUNT(SELECT * FROM partnertable), COUNT(SELECT * FROM customertable)');
To then access the values, you would refere to $result based on the position in the array, ie. $result[0] would be the first value, $result[1] the second and so on.
If you need to specify the items for the counts (such as active users, active customers etc) add where clauses into the select statements within the count expression
Eg. SELECT * FROM usertable WHERE active="yes"
Once you have the data you need, you can then edit the source file where you require them to be displayed and decide where to place them using a php echo to the html stream

Related

how to use relation table when using sqldataprovider

please help I dont know how to get relation table when using sqldataprovider. Anyone understand how to use relation model?
$model = new Finalresult();
$searchModel = new FinalresultSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT finalresult.bib,
finalresult.series_id,
finalresult.category_id,
GROUP_CONCAT(DISTINCT finalresult.point ORDER BY series.serie_seri_no DESC) AS seriPoint
FROM finalresult, series GROUP BY finalresult.bib',
'key' => 'bib',
]);
I'm trying to get relation table:
'attribute'=>'category_id',
'width'=>'300px',
'value'=>function ($model, $key, $index, $widget) {
return $model->category->category_name;
},
then getting trying to non-object
You can't use relations with SqlDataProvider, because each single result will be presented as array, for example:
[
'id' => 1,
'name' => 'Some name',
'category_id' => 1,
],
For example, you can access category_id as `$model['category_id'].
SqlDataProvider is for very very complex queries, your query can easily be written as ActiveQuery and you can use ActiveDataProvider and get all advantages of that (relations, etc.).
You can find category by id, but it will be lazily loaded that means amount of queries is multiplied by number of rows.
With ActiveDataProvider and relations you can use eager loading and reduce amount of queries. Read more in official docs.
Grid Columns example in documentation
try to change "value" to
'value'=> function($data) {
return $data['category']['category_name'];
}

Implement tab view with sorting and pagination in Yii

Am trying to bring a tab view with list , sorting and pagination in Yii. I have 2 tables named service_request and favourites where the datas come from. In that page I need to display the service request and favourites added date and some other fields. I tried to implement it with join , but it is not successfully listing the datas from service request. In my controller action I had added
$criteria = new CDbCriteria;
$criteria->select = 'favourite_notes,s.service_request_id';
$criteria->join = 'LEFT JOIN service_request s ON service_request_id = 1';
$criteria->condition = 'favourite_type = 1';
$data=new CActiveDataProvider('ProviderFavourite',array('criteria'=>$criteria,'pagination'=>array('pageSize'=>1)
));
$this->renderPartial('viewtest', array(
'ModelInstance' => ProviderFavourite::model()->findAll($criteria),
'dataProvider'=>$data,
));
In viewtest I had provided,
$this->widget('zii.widgets.CListView', array('dataProvider'=>$dataProvider,'itemView'=>'view',
'id'=>'request-list',
'template' => ' {items}{pager}',
));
In view page, I had fetched the data
echo $data->service_request;
echo $data->favourite_notes;
All your suggestions are welcome..
You can build your own function for sorting using CDBCriteria
at model side you can orderby and orderById pass through get or post
$criteria=new CDbCriteria;
$criteria->alias='b';
$criteria->order='b.'.$orderById.' '.$orderBy.',b.type asc,b.smallimage desc';
$dataProvider=new CActiveDataProvider($this->tableName(), array(
'criteria' => $criteria,
'pagination'=>array(
'pageSize'=>$limit,
),
));
Now at view side you can do like here Web pager is pagination class and extrapara is array of parameter those need for pagination
$this->widget('application.extensions.WebPager',
array(
'cssFile'=>false,
'pages' => $pagination,
'extraPara'=>$extraPara,
'id'=>'link_pager'
));

How can I insert data from a table from sql into a dropdown list in zend framework 2?

I need to insert multioptions to a dropdown list, options taken from a table from my database.
I created the elements like:
$this->add(array(
'name' => 'company',
'type' => 'Zend\Form\Element\Select',
//'multiOptions'=> $options,
'options' => array(
'label' => 'Company',
),
'attributes' => array(
'style' => "float:right;",
),
));
I want to choose from a dropdown list some values that are in a table in my database. For example I have the entity Contacts and I need to choose for the contact a company that is in a table named companies in the database.
After reading on zend framework's site, I tried using this code:
$params = array(
'driver'=>'Pdo_Mysql',
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'dbname' =>'myDataBase'
);
$db = new \Zend\Db\Adapter\Adapter($params);
$sql= new Sql($db);
$select = $sql->select();
$select ->from('companies')
->columns(array('id','company_name'))
->order(" 'company_name' ASC");
I also read on some other sites that I could use a function:
$options = $sql->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
but it seems it doesn't exist anymore in Zend Framework 2.
Please guys, give me a hand. If the code isn't good and you have a better idea, please tell me.
Thanks in advance!
This is just a quick and dirty answer, but i guess it can get you started.
Create a ServiceFactory, this should be done in a separate factory class instead of a closure, but i still use a closure - faster to write ;)
Get the config from the ServiceLocator so you have access to the DB-Params
Create your default SQL Stuff to retriefe the value_options
Populate the value_options using the setValueOptions($valueOptions) function of your given form-element
Module.php getServiceConfig()
return array(
'factories' => array(
'my-form-factory' => function($serviceLocator) {
$form = new My\Form();
$config = $serviceLocator->get('config');
$db = new \Zend\Db\Auth\Adapter\Adapter($config['dbParams']); //or whatever you named the array key
$sql = //do your SQL Stuff
// This is a fake array, it should be your $sql result in the given format
$result = array('value' => 'label', 'value2' => 'label2');
$form->get('elementToPopulate')->setValueOptions($result);
return $form;
}
)
);
SomeController.php someAction()
$form = $this->getServiceLocator()->get('my-form-factory');
return new ViewModel(array(
'form' => $form
));
I hope this gets you started
you have to add that field validation on controller for setting value in it.
$select = $db->select()->where("state_code = ?",$arr["state_code"]);
$resultSet = $cityObj->fetchAll($select);
$cityArr = $resultSet->toArray();
$city_ar = array();
foreach($cityArr as $city){
$city_ar[$city['id']] = $city['company'];
}
$form->company->setMultiOptions($city_ar);
$form->company->setValue($val["company"]);
by using this code drop down of country have the value that are in resultset array ($resultSet).

Filtering theme_table in Drupal

I just created a data table based on a query and displayed it successfully using theme_table().
Now, I'd like to add some filters to the table but have no idea how to proceed.
Is there a built-in feature that allow me to do this easily, or should I manually add a form and update the query/redisplay the results each time the user selects something?
Thanks for your help!
I think you want to use pager_query and tablesort_sql: it's especially made for creating tables of data with pagination and sorting capabilities (and themes usually theme such tables nicely out of the box).
Example:
<?php
// The regular query without sorting or pagination parameters
$sql = 'SELECT cid, first_name, last_name, company, city FROM {clients}';
// Number of rows per page
$limit = 20;
// List of table columns ("field" is the matching database column from the sql query)
$header = array(
array('data' => t('Name'), 'field' => 'last_name', 'sort' => 'asc'),
array('data' => t('Company'), 'field' => 'company'),
array('data' => t('City'), 'field' => 'city')
);
// Calculates how to modify the SQL query according to the current pagination and sorting settings
// Then performs the database query
$tablesort = tablesort_sql($header);
$result = pager_query($sql . $tablesort, $limit);
$rows = array();
while ($client = db_fetch_object($result)) {
$rows[] = array(l($client->last_name.', '.$client->first_name, 'client/'.$client->cid), $client->company, $client->city);
}
// A message in case no results were found
if (!$rows) {
$rows[] = array(array('data' => t('No client accounts created yet.'), 'colspan' => 3));
}
// Then you can pass the data to the theme functions
$output .= theme('table', $header, $rows);
$output .= theme('pager', NULL, $limit, 0);
// And return the HTML output
print $output;
?>
(I added comments, but the original version of the example comes from this page)
Alternatively, maybe you don't need to make a module at all if you're just trying to make a page that displays a list of data, you may prefer using the Views module.

Custom Query Pagination Cakephp

I have a custom query in my controller and I would like to implement the custom query pagination I found on cakephp.org but their example is not similar to mine. Can someone please help me paginate this result in my view:
$cars = $this->Car->query(" select Car.id, Car.make, Car.model, Car.year, Car.description, CarImage.thumbnail
from cars Car
inner join car_images CarImage on Car.default_image_id = CarImage.id
where Car.make like '" . $category . "'
order by Car.created DESC
limit 10");
$this->set('cars', $cars);
Implement paginate and paginateCount in your model:
function paginate($conditions, $fields, $order, $limit, $page, $recursive, $extra)
{
return $this->query('SELECT ...');
}
function paginateCount($conditions, $recursive, $extra)
{
return $this->query('SELECT COUNT(.....');
}
Also check out the paginate function in: cake/libs/controller/controller.php
This looks like it should be able to be done without resorting to using custom pagination.
You should set in the following relationships in your models:
Car hasMany (or hasOne) CarImage CarImage belongsTo Car
Then you should be able to get this exact data using the following:
<?php
class CarsController extends AppController {
var $paginate = array('limit'=>'10',
'order'=>'Car.created',
'fields'=>array('Car.model','Car.year','Car.description',
'CarImage.thumbnail'));
function test() {
// not sure where you are getting the where clause, if its from some form
// you'll want to check look in $this->data
$category = "somevalue";
// set the LIKE condition
$conditions = array('Car.make LIKE' => '%'.$category.'%');
// apply the custom conditions to the pagination
$this->set('cars', $this->paginate($conditions);
}
}
?>
For more information on complex find conditions (which can be applied to paginate by passing in an array like I did in the above example): http://book.cakephp.org/view/74/Complex-Find-Conditions
In Cake 3 you can use de the deafult paginator with function find() .
Follow the example:
$query = $this->Car->find()
->select(['Car.id', 'Car.make','Car.model','Car.year','Car.description','CarImage.thumbnail'])
->join([
'table' => 'CarImage',
'alias' => 'CarImage',
'type' => 'INNER',
'conditions' => 'CarImage.id = Car.default_image_id,
])
->where(['Car.make LIKE' => '%$category%'])
->order(['Car.created' => 'DESC'])
->limit(50)
$cars = $this->paginate($query);
$this->set(compact('cars'));
$this->set('_serialize', ['cars']);
mysql limit clause support volume and offset, so 10 results per page....
select * from table limit 0, 10
page 1
select * from table limit 10, 10
page 2
select * from table limit 20, 10
page 3
select * from table limit ($page-1)*$perPage, $perPage
Generic
mysql limit clause support volume and offset, so 10 results per page....