Codeigniter - Calling a model method within same model is buggy - php

I am trying to call a model method within same model and its not working as intended. Here is my class with two methods which do not work
class mymodel extends CI_Model{
public function __construct(){
parent::__construct();
$this->tablea = 'tablea';
$this->tableb = 'tableb';
}
public function saveData($data){
$dataCopy['revisionkey'] = $this->getRevisionKey($data['id']);
//check and condition revision key to be int with +1 from last one
$this->db->insert($this->tableb, $dataCopy);
$this->db->where('id', $id);
return $this->db->update($this->user_table, $data) ? true : false;
}
public function getRevisionKey($id){
$this->db->select($this->revision_tablea.'.revisions_number as revisions_number')
->from($this->revision_tablea)
->where($this->revision_tablea.'.id', $id)
->order_by($this->revision_table.'.revisions_number', 'asc')
->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
return $query->row_array();
}else{
return 0;
}
}
}
Now method getRevisionKey() should produce a query like following
SELECT `tableb`.`revisions_number` as revisions_number FROM (`tableb`) WHERE `tableb`.`id` = '26' ORDER BY `tableb`.`revisions_number` asc LIMIT 1
but it produces a query like following
SELECT `tableb`.`revisions_number` as revisions_number FROM (`tableb`) WHERE `id` = '26' AND `tableb`.`id` = '26' ORDER BY `tableb`.`revisions_number` asc LIMIT 1
This of course is due to same method being called within the model, this method works fine if used outside of model. Any solution to this problem?
EDIT
Rewriting the getRevisionKey() fixes this. Here is the new version
public function getRevisionKey($id){
$sqlQuery = $this->db->select($this->revision_tablea.'.revisions_number as revisions_number')
->from($this->revision_tablea)
->order_by($this->revision_table.'.revisions_number', 'asc')
->limit(1);
$query = $sqlQuery->where($this->revision_tablea.'.id', $id)->get();
if ($query->num_rows() > 0){
return $query->row_array();
}else{
return 0;
}
}

Here is a simple hack that will give you exactly where you are making a mistake.
Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
And save it. Before running the function i mean calling
$this->db->get() // Use $this->db->from() instead
use
$query = $this->db->_compile_select()
and echo $query;
These two functions also help in subquery in codeigniter active record.
How can I rewrite this SQL into CodeIgniter's Active Records?

Related

Codeigniter subtracting time and making an selection from database in model

I am building a library project where a user needs to know which books have not been submitted on time.So for that i have stored book_returning_date already in the database.However my issue here is that i need to know how to select the dates in model which have crossed there return date by comparing with today date.My model code is here as follow:
public function timecalculations($table){
$query= $this->db->get_where('issue_books',array('department_id'=>$table));
return $query->result();
}
and my controller is as here follows:
public function latebooks(){
$this->load->model('Time');
$id=$this->session->userdata('userid');
$this->load->model('Department');
$table=$this->Department->selecttable($id);
foreach($table as $q){}
$table = $q->department_name;
$table = strtolower($table);
$run=$this->Time->timecalculations($table);
$this->load->view('Books/datetime',['query'=>$run]);
}
I am new in codeigniter so please forgive as i may be having a little problem with the logic.Thanks in advance!
try this
public function timecalculations($table){
$query= $this->db->where('book_returning_date < CURRENT_DATE()', NULL, FALSE)->get($table);
return $query->result();
}
add another where clause,
public function timecalculations($table){
$this->db->where('book_returning_date < NOW()');
$query = $this->db->get($table);
return $query->result();
}
this will return the rows where current date is already crossed book_returning_date
i am assuming u are saving the book_returning_date in the following format 'yyyy-mm-dd H:i:s'
probably like this and sorry if i'm mistake
First need to Set Library Session setting in config
for model :
public function timecalculations($table){
$condition = 'department_id = "'.$table.'"';
$this->db->select('issue_books');
$this->db->where($condition);
$query= $this->db->get();
return $query->result();
}
for controller i'm not sure but like this :
public function __construct() {
$this->load->model('Time', 'time');
$this->load->model('Department', 'departement');
$this->load->library('Session');
}
public function latebooks($id){
$id=$this->session->userdata('userid');
$table=$this->department->selecttable($id);
foreach($table as $q){ (probably i'm wrong)
$table = $q->department_name; (probably i'm wrong)
} (probably i'm wrong)
$table = strtolower($table); (probably i'm wrong)
$run=$this->time->timecalculations($table);
$this->load->view('Books/datetime',['query'=>$run]);
}
Try this
In Controller
public function latebooks()
{
$this->load->model('Time');
$this->load->model('Department');
$id = $this->session->userdata('userid');
$result = $this->Department->selecttable($id); # Changed
$table = $result[0]['department_name']; # Changed
$table = strtolower($table); # Changed
$run = $this->Time->timecalculations($table);
$this->load->view('Books/datetime',['query'=>$run]);
}
In Model
public function timecalculations($table)
{
$query = $this->db->get_where('issue_books',array('department_id'=>$table));
$result = $query->result_array();
return $result;
}

Return a single row in model, pass it to controller and view - Codeigniter

Sorry for posting such a noob question, but I've had hard times when working with returning a single
row from database and pass it to model. Here's my method from my model:
public function test($user_id)
{
$query = $this->db->query("SELECT COUNT(*) AS test FROM test WHERE user_id = '.$user_id.'");
return $query->first_row('array');
}
Here's an example of my controller with some other returned value from my model:
class MY_Controller extends CI_Controller
{
public $layout;
public $id;
public $data = array();
public function __construct()
{
parent::__construct();
$this->output->nocache();
$this->load->model('subject_model');
$this->load->model('user_model');
$this->load->model('survey_model');
$this->id = $this->session->userdata('user_id');
$this->data['check_if_already_posted_it_survey'] = $this->survey_model->checkIfAlreadyPostedSurvey('it_survey', $this->id);
$this->data['check_if_already_posted_lvis_survey'] = $this->survey_model->checkIfAlreadyPostedSurvey('lvis_survey', $this->id);
$this->data['test']= $this->survey_model->test($this->id);
$this->layout = 'layout/dashboard';
}
I can pass all the values from that data array to my view except "test". I've basically tried everything.
CheckIfAlreadyPostedSurvey method will return
number of rows with num_rows and I can easily print the value from them in my view by writing:
<?=$check_if_already_posted_it_survey?>
What should I do to print out that "test" in my view?
Thanks in advance and apologizes...
I probably got the question wrong, but have you tried
echo $this->survey_model->test($this->id);
Try this:
public function test($user_id)
{
$query = $this->db->query("SELECT COUNT(*) AS test FROM test WHERE user_id = '".$user_id."'");
return $query->row()->test;
}
This will return a single row as an object and then the referenced row name, which in this case is test.
The following will also work.
public function test($user_id)
{
$query = $this->db->query("SELECT * FROM test WHERE user_id = '".$user_id."'");
return count($query->result());
}
You also messed up the quoting in your SQL statement.

Unable to assign variable value in model constructor

I am playing with Laravel models and I need one to return a value that is not in the db table but it comes by running a model method. This method runs a query that groups and count grouped results.
The model method works just fine but I don't seem to be able to pre-fill the $quantity variable within the constructor with something different than 0.
So this is an excerpt of the model:
public $quantity;
function __construct($attributes = array(), $exists = false) {
parent::__construct($attributes, $exists);
$this->quantity = $this->quantity();
}
public function quantity()
{
$query = DB::table('carts_shopping')
->select('cart_id', DB::raw('COUNT(*) AS quantity'))
->where('cart_id',$this->cart_id)
->groupBy('cart_id')
->first();
return ($query) ? $query->quantity : 0;
}
While this is how I am trying to retrieve the results from controller:
$cartitems = Auth::user()->cartshopping;
foreach ($cartitems as $cartitem)
{
echo $cartitem->name;
echo $cartitem->quantity;
}
As you may guess 'cartshopping' comes from the user model being related with the model excerpt I pasted.
I also noticed that quantity() method gets called and it returns 0 all the time as if $this->cart_id was empty and, changing $this-cart_id with a real value the query itself doesn't even get executed.
Thanks a lot for any suggestion you guys can share.
Have you tried accessing the properties using $this->attributes?
public $quantity;
function __construct($attributes = array(), $exists = false) {
parent::__construct($attributes, $exists);
$this->quantity = $this->quantity();
}
public function quantity() {
$query = DB::table('carts_shopping')
->select('cart_id', DB::raw('COUNT(*) AS quantity'))
->where('cart_id', $this->attributes['cart_id'])
->groupBy('cart_id')
->first();
return ($query) ? $query->quantity : 0;
}
Failing that, you could try using the Eloquent accessors, which would be the best way to do it. This would make it dynamic as well, which could be useful.
class YourModel {
// Normal model data here
public function getQuantityAttribute() {
$query = DB::table('carts_shopping')
->select('cart_id', DB::raw('COUNT(*) AS quantity'))
->where('cart_id', $this->attributes['cart_id'])
->groupBy('cart_id')
->first();
return ($query) ? $query->quantity : 0;
}
}

Code Igniter Count Function

What I want to do is I want to count the total records from the table called "songs_tbl" from my database. So I wrote this function in controller.
private function getHeaderInfo()
{
$total_songs = $songs->count('distinct songs_tbl.song_id');
$this->mysmarty->assign('total_songs',$total_songs);
}
I got this error
Fatal error: Call to a member function count() on a non-object in
Any suggestion ? Thank you.
With Regards,
I think you are looking for:
$this->db->count_all('songs_tbl');
or if you want the distinct in there you will need to do something like this:
$this->db->select('song_id');
$this->db->distinct();
$this->db->from('songs_tbl');
$query = $this->db->get();
return $query->num_rows();
As there is/was? an issue with using count_all_results() function and DISTINCT
EDIT
I have never used smarty but based on the code in the question I imagine something like this might work, please correct me if I am wrong:
private function getHeaderInfo()
{
$total_songs = get_all_songs();// This function should be called through a model
$this->mysmarty->assign('total_songs',$total_songs);
}
function get_all_songs(){ //THIS SHOULD BE IN A MODEL
$this->db->select('song_id');
$this->db->distinct();
$this->db->from('songs_tbl');
$query = $this->db->get();
return $query->num_rows();
}
Edit 2
My suggested layout would be something along these lines (UNTESTED) using CodeIgniter WITHOUT smarty:
Model Song.php
class Song extends CI_Model {
//Constructor and other functions
function count_all_songs(){
$this->db->select('song_id');
$this->db->distinct();
$this->db->from('songs_tbl');
$query = $this->db->get();
return $query->num_rows();
}
}
Controller Songs.php
class Song extends CI_Controller {
//Constructor and other functions
function index(){ //This could be any page
$this->load->model('Song'); //Could be in constructor
$total_songs = $this->Song->count_all_songs();
$this->load->view('songs_index.html', array('total_songs' => $total_songs));
}
}
View songs_index.html
<html><head></head><body>
Total Songs: <?php echo $total_songs ?>
</body></html>
You could query the table and request a count from the table itself, like this:
$result = mysql_query(SELECT count(*) FROM songs_tbl);
Try this
echo $this->db->count_all('songs_tbl');
It permits you to determine the number of rows in a particular table.
you can use this
$query = $this->db->get('distinct');
if($query->num_rows())
{
return $query->num_rows();
}else{
return 0;
}

Doctrine : how to manipulate a collection?

With symfony && doctrine 1.2 in an action, i try to display the top ranked website for a user.
I did :
public function executeShow(sfWebRequest $request)
{
$this->user = $this->getRoute()->getObject();
$this->websites = $this->user->Websites;
}
The only problem is that it returns a Doctrine collection with all the websites in it and not only the Top ranked ones.
I already setup a method (getTopRanked()) but if I do :
$this->user->Websites->getTopRanked()
It fails.
If anyone has an idea to alter the Doctrine collection to filter only the top ranked.
Thanks
PS: my method looks like (in websiteTable.class.php) :
public function getTopRanked()
{
$q = Doctrine_Query::create()
->from('Website')
->orderBy('nb_votes DESC')
->limit(5);
return $q->execute();
}
I'd rather pass Doctrine_Query between methods:
//action
public function executeShow(sfWebRequest $request)
{
$this->user = $this->getRoute()->getObject();
$this->websites = $this->getUser()->getWebsites(true);
}
//user
public function getWebsites($top_ranked = false)
{
$q = Doctrine_Query::create()
->from('Website w')
->where('w.user_id = ?', $this->getId());
if ($top_ranked)
{
$q = Doctrine::getTable('Website')->addTopRankedQuery($q);
}
return $q->execute();
}
//WebsiteTable
public function addTopRankedQuery(Doctrine_Query $q)
{
$alias = $q->getRootAlias();
$q->orderBy($alias'.nb_votes DESC')
->limit(5)
return $q
}
If getTopRanked() is a method in your user model, then you would access it with $this->user->getTopRanked()
In your case $this->user->Websites contains ALL user websites. As far as I know there's no way to filter existing doctrine collection (unless you will iterate through it and choose interesting elements).
I'd simply implement getTopRankedWebsites() method in the User class:
class User extends BaseUser
{
public function getTopRankedWebsites()
{
WebsiteTable::getTopRankedByUserId($this->getId());
}
}
And add appropriate query in the WebsiteTable:
class WebsiteTable extends Doctrine_Table
{
public function getTopRankedByUserId($userId)
{
return Doctrine_Query::create()
->from('Website w')
->where('w.user_id = ?', array($userId))
->orderBy('w.nb_votes DESC')
->limit(5)
->execute();
}
}
You can also use the getFirst() function
$this->user->Websites->getTopRanked()->getFirst()
http://www.doctrine-project.org/api/orm/1.2/doctrine/doctrine_collection.html#getFirst()

Categories