I'm trying to filter the results of a query. A user can only see companies that have the same company_group_id as his, so I tought of adding that condition in the beforeFind function of my model.
function beforeFind($queryData) {
App::uses('CakeSession', 'Model/Datasource');
$user = CakeSession::read('Auth.User');
$queryData['conditions']['Company.company_group_id'] = $user['company_group_id'];
parent::beforeFind($queryData);
}
I can see this condition appear when I pr() my $queryData
Array
(
[conditions] => Array
(
[Company.company_group_id] => 2
)
)
Unfortunately, the resulting query when I call my paginate ignores this condition
SELECT `Company`.`id`, ... WHERE 1 = 1 GROUP BY `Company`.`id` ORDER BY `Company`.`name` asc LIMIT 10
Am I doing this correctly? Or is there another way to show the correct records to the user?
You must configure the pagination behavior in your controller's action (more about this here):
//obtaining the company_group_id
$user = CakeSession::read('Auth.User');
$id = $user['company_group_id'];
//setting the pagination conditions (similar to a find())
$this->paginate = array(
'conditions' => array('Company.company_group_id' => $id),
);
$data = $this->paginate('Company');
$this->set('data', $data);
Related
I am using cakephp 2x and I'm trying to display the max count of my "Users" table
heres my controller
$getid = $this->User->find('all',
array('fields' => array('Max(User.id)'))
);
$users = $this->set('users',$getid);
its not working.
Max count ? you mean the last id when i see your function .
If yes,
You must use getLastInsertId function on your model
Example : $this->User->getLastInsertID()
Normally that must do the job
Or you can also find the first user by order desc
$this->User->find('first',
array('fields' => User.id','order' => array('User.id' => 'desc)))
);
I have two models set up for an array. Basically, what I want to achieve is to get the first next entry from the database based on the order ID I have set up.
So, I send the ID 4, I find the entry with the ID 4 which has the order ID 15. Then I want to get the first next item after it, which should have the order ID 16. I tried incrementing with +1 after the order ID, but it just doesn't work.
With my current code I get the same array twice.
function first($id_domain) {
$this->db->select ( '*' );
$this->db->from ( 'domains' );
$this->db->where ( 'id_domain', $id_domain);
$result = $this->db->get ();
return $result->result_array ();
}
function second ($result) {
$this->db->select ( '*' );
$this->db->from ( 'domains' );
$this->db->where ( 'order', $result[0]['order'] + 1 ); //code that should get me the next entry, but doesn't work...
$this->db->where ( 'parent', $result[0]['parent'] );
$result2 = $this->db->get ();
return $result2->result_array ();
}
The problem is not due to your code, but it may be due to the records in the database: either they are non-existing for that specific condition or your matching is not entirely correct.
If you are using CodeIgniter I suggest you to alter your second function to this:
function second($result) {
$whereConds = array(
'order' => intval($result[0]['order'] + 1),
'parent'=> $result[0]['parent']
);
//if you don't have firephp print/echo/var_dump as you normally would
$this->firephp->log($whereConds);
$query = $this->db->get_where('domains', $whereConds);
$this->firephp->log($this->db->last_query());
if ($query->num_rows() <= 0) {
$this->firephp->log('No results');
return array();
} else {
return $query->result_array();
}
}
This way you can track the problem accurately.
Btw, you can also use the $offset parameter in the get_where to get the next id (perhaps just with the parent condition, since you know they are ordered sequentially):
$limit=1;
$offset=intval($result[0]['order'] + 1);//adjust depending on the parent condition below: it can be just an integer such as 2
$whereConds = array(
'parent'=> $result[0]['parent']
);
$query = $this->db->get_where('domains', $whereConds, $limit, $offset);
I'm using the WP MVC plugin to create a plugin which provides a database of names as part of my Wordpress website.
The below controller retrieves the right information from 2 database tables, but suddenly pagination is not working anymore. Do I need to use paginate() instead of find()? If yes, how would a similar query look using paginate()? Unfortunately there are no examples available.
Thanks!
names_controller.php
<?php
class NamesController extends MvcPublicController {
public function index() {
$objects = $this->Name->find(array(
'joins' => array('Origin'),
'selects' => array('Origin.id', 'Origin.origin', 'Name.id', 'Name.name', 'Name.gender', 'Name.meaning', 'Name.origin_id'),
'page' => 1,
'per_page' => 20,
'conditions' => array(
'Name.name LIKE' => 'A%'
)
));
$this->set('objects', $objects);
}
}
?>
=================== UPDATE ======================
I replaced the find() with paginate() unfortunately the join doesn't work anymore. Furthermore it IGNORES e.g. page, per_page etc parameters.
Anyone an idea?
$params = $this->params;
$params['page'] = empty($this->params['page']) ? 1 : $this->params['page'];
$params['per_page'] = 20;
$params['joins'] = array('Origin');
$params['selects'] = array('Origin.id', 'Origin.origin', 'Name.id', 'Name.name', 'Name.gender', 'Name.meaning', 'Name.origin_id');
$collection = $this->Name->paginate($this->params);
$this->set('objects', $collection['objects']);
$this->set_pagination($collection);
I'm having trouble getting pagination to work when conditions are involved in the query. In my OrdersController I have the following pagination to display all of the entires and it works perfectly
$order_list = $this->Paginate('Order');
$this->Set('orders', $order_list);
When I try to find the orders for a given user it immediately throws an error and I can't even figure out what it's related to.
$order_list = $this->Paginate = array(
'conditions' => array('Order.userid' => $id)
);
$data = $this->Paginate('orders', $order_list);
$this->set(compact('data'));
In my OrdersController I also have listed:
public $paginate = array(
// other keys here.
'maxLimit' => 20
);
When I try to run this I get an error that says "An Internal Error Ocurred" which isn't helpful at all.
When I print the search results for $order_list it just spits out the parameters I'm searching for, so I don't even think it's searching.
Array ( [conditions] => Array ( [Order.userid] => 4 ) )
It basically just tells me what I'm searching for and doesn't actually search the orders table for the values.
Try this
$data = $this->paginate('Order', array('Order.userid' => $id));
$this->set(compact('data'));
You seem to mix two approaches of defining extra parameters to paginate by. See CookBook for more info.
I have two models in an 1:n relation and I just want to load the count of the related items.
First one is the table/model "Ad" (one) which is related to "AdEvent" (many). AdEvents has a foreign key "ad_id".
In the controller I can use it that way and it loads the related AdEvent-records.
$this->Ad->bindModel(array('hasMany' => array(
'AdEvent' => array(
'className' => 'AdEvent',
'foreignKey' => 'ad_id',
))));
Now I just need the count without the data and I tried with param "fields" and "group" a COUNT()-statement, but in that case the result is empty. I also changed the relation to "hasOne", but no effect.
Any idea how to use the Cake-magic to do that?
EDIT:
With simple SQL it would look like this (I simplyfied it, a.id instead of a.*):
SELECT a.id, COUNT(e.id) AS count_events
FROM cake.admanager_ads AS a
JOIN ad_events AS e ON e.ad_id = a.id
GROUP BY a.id
LIMIT 50;
You can always do a manual count of course. This is what I almost always end up doing because I almost always have the data loaded already for some other purpose.
$Ads = $this->Ad->find('all')
foreach ($Ads as $Ad) {
$NumAdEvents = array(
$Ad['Ad']['id'] => sizeof($Ad['AdEvents']),
)
}
debug($NumAdEvents);
die;
Or you can use a find('count'):
$id_of_ad = 1; //insert your ad id here, or you can search by some other field
$NumAdEventsAtOneAd = $this->AdEvent->find('count', array('conditions' => array(
'AdEvent.ad_id' => $id_of_ad,
)));
debug($NumAdEventsAtOneAd);
die;