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)))
);
Related
I have a very complex setup on my tables and achieving this via any of the find() methods is not an option for me, since I would need to fix relationships between my tables and I don't have the time right now, so I'm looking for a simple fix here.
All I want to achieve is run a query like this:
SELECT MAX( id ) as max FROM MyTable WHERE another_field_id = $another_field_id
Then, I need to assign that single id to a variable for later use.
The way I have it now it returns something like [{{max: 16}}], I'm aware I may be able to do some PHP on this result set to get the single value I need, but I was hoping there was already a way to do this on CakePHP.
Assuming you have a model for your table and your are using CakePHP 2.x, do:
$result = $this->MyTable->field('id', array('1=1'), 'id DESC');
This will return a single value.
see Model::field()
This example is directly from the CakePHP documentation. it seems you can use the find method of a model to get count
$total = $this->Article->find('count');
$pending = $this->Article->find('count', array(
'conditions' => array('Article.status' => 'pending')
));
$authors = $this->Article->User->find('count');
$publishedAuthors = $this->Article->find('count', array(
'fields' => 'DISTINCT Article.user_id',
'conditions' => array('Article.status !=' => 'pending')
));
I have code like this:
$this->db->select('title')->from('entries')->where('id', 1);
$query = $this->db->get();
echo $query->row('title');
Which echoes the title from the entries table where the id is equal to 1.
Why doesn't it work without the 'title in row function?
echo $query->row();
As it returns the first row?
Why do I have to have 'title' in both places ($query->row and $this->db->select), in order for this to work? It doesn't make sense to me.
Can anybody explain how this works, supposedly provide with alternative ways to get the value from the database?
$this->db->select('title')->from('entries')->where('id', 1);
Generates
SELECT title FROM entries WHERE id = 1
$query retrieves the result in an array:
array( [0] => array( [title] => 'your title' ))
row('title') returns the title column from the first row of your result array.
The reason you need to tell it which column to get is because row and get can be used with many columns.
Currently i have table with posts, each posts has an id.
For a moment, only one posts exists, with id id = 92.
if i execute following code, i will get not false, but post with id=92:
$post = NewsPost::findFirst(['id' => 1]);
var_dump($post->id); // gives 92
Seems to be very strange logic..
What method could be used to retrieve post by id, and that will return false/throw exception if there is no such entity?
Try this:
$post = NewsPost::findFirst("id = 1");
or
$post = NewsPost::find(
array(
"conditions" => "id = ?0",
"bind" => array(0 => 1)
)
);
I use:
$instance = Model::findFirst($id);
Where $id is a primary key.
Use
NewsPost::findFirst(['id = 1']);
or
NewsPost::findFirst(1)
You should use:
NewsPost::findByid(1);
Where 'id' can be replaced by any of your model's properties. For example:
NewsPost::findByDescription('Description');
NewsPost::findByyourprop(yourpropval);
You can then count() the return value count($result) to determine if you received any records.
Note: I have also found the string searches to be case in-sensitive.
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);
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;