when i try to construct a query to my db in my model like
class Application_Model_DbTable_Resume extends Zend_Db_Table_Abstract
{
protected $_name = 'users';
public function getFiveLastResume (){
$select= $db->select()->from('users')->order("id DESC")->limit(5);
$stmt = $db->query($select);
$row = $stmt->fetchAll();
return $row;
}
}
so i have an error Notice: Undefined variable: db
if I write adapter before query
$db = Zend_Db::factory('PDO_MYSQL',array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'dbname' => 'sport'
));
thats work good. why does my adapter not work ?
my application.ini contain right database config,cuz more simply queries work out good without including adapter. im noob in zend, thanks
$db is undefined in the local scope which is why you get the error.
Since you are inside a DbTable object, you can use $this to get the DB adapter:
public function getFiveLastResume () {
$select = $this->select()->from('users')->order("id DESC")->limit(5);
$stmt = $select->query();
$row = $stmt->fetchAll();
return $row;
}
Anywhere else in your application, you should be able to get a reference to the default DB adapter using:
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select()->from('table')...;
This of course assumes you have created a Zend_Db_Table object and set it as the default adapter.
Related
I'm using Eloquent 5.* on my CodeIgniter3.1.1 project, Everything works fine however i want to check the queries executed when a request is processed,
After some googling i came accross Using Eloquent ORM inside CodeIgniter with added Query Logging and having CI Profiler enabled i see "No Queries Executed",
my database.php configuration for Eloquent looks as below
//Eloquent ORM database connection
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection(array(
'driver' => 'mysql',
'dsn' => 'mysql:host=localhost; dbname=communit_iwa_test charset=utf8;',
'host' => $db['default']['hostname'],
'database' => $db['default']['database'],
'username' => $db['default']['username'],
'password' => $db['default']['password'],
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => $db['default']['dbprefix'],
));
$capsule->setAsGlobal();
$capsule->bootEloquent();
$events = new Illuminate\Events\Dispatcher;
$events->listen('illuminate.query',function($query, $bindings, $time,$name) {
// Format binding data for sql insertion
foreach ($bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else if (is_string($binding)) {
$bindings[$i] = "'$binding'";
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $query);
$query = vsprintf($query, $bindings);
// Add it into CodeIgniter
$db = & get_instance()->db;
$db->query_times[] = $time;
$db->queries[] = $query;
});
$capsule->setEventDispatcher($events);
/* End of file database.php */
/* Location: ./application/config/database.php */
Your Help is appreciated in advance
To view executed eloquent queries usegetQueryLog() method of the classIlluminate\Database\Capsule\Manager;
in short
Include Illuminate\Database\Capsule\Manager class in your controller or model as use Illuminate\Database\Capsule\Manager as Capsule;
use Capsule::getQueryLog() method to view an array of all queries executed in Eloquent ORM
I have a tables named:
client (id, alias)
post (id, subject)
post_client (id, post_id, client_id)
Many clients can be joined to a post.
Using Zend DB Table abstract I have started to build a model, here are the classes:
ORM_Post
class ORM_Post extends Zend_Db_Table_Abstract {
protected $_name = 'Post';
protected $_dependentTables = array('ORM_Post_Client');
}
ORM_Client
class ORM_Client extends Zend_Db_Table_Abstract {
protected $_name = 'Client';
protected $_dependentTables = array(
'ORM_Post_Client'
);
}
ORM_Post_Client
class ORM_Post_Client extends Zend_Db_Table_Abstract {
protected $_name = 'Post_Client';
protected $_referenceMap = array(
'post' => array(
'columns' => 'post_id',
'refTableClass' => 'ORM_Post',
'refColumns' => 'id'
),
'client' => array(
'columns' => 'client_id',
'refTableClass' => 'ORM_Post_Client',
'refColumns' => 'id'
)
);
}
What I was hoping todo is call an instance of the Post and then load the clients associated aswell as loading an instance of the client and load all posts associated.
So I did this:
$post = new ORM_Post();
$results = $post->fetchAll();
foreach ($results as $key => $result){
$row = $results->current();
$client = $row->findDependentRowset('ORM_Post_Client','client');
}
and I get
Reference rule "client" does not reference table ORM_Post
I have battled with this for hours and cannot see where I'm going wrong. Am I to declare the Post_Client joins inside the client and post model also?
EDIT
Here is what I was after:
$post = new ORM_Post();
$results = $post->fetchAll();
$return = array();
foreach ($results as $result){
$row = $post->find($result->id)->current();
$return[$result->id] = $row->toArray();
$return[$result->id]['clients'] = $row->findManyToManyRowset('ORM_Client', 'ORM_Post_Client')->toArray();
}
return $return;
Thanks for the advice guys, you put me on the right track
in your ORM_Post_Client it should be
'client' => array(
'columns' => 'client_id',
'refTableClass' => 'ORM_Client', //instead of ORM_Post_Client
'refColumns' => 'id'
)
refTableClass => The class name of the parent table. Use the class
name, not the physical name of the SQL table (documentation)
also i think your loop should be :
foreach ($results as $result){
$row = $results->current();
$clients = $row->findDependentRowset('ORM_Post_Client','post');
}
because you are looking for clients of a post which means that post is your rule
($row->findDependentRowset($table, [$rule]); )
This as presented won't work, honestly it makes no sense.
$post = new ORM_Post();
$results = $post->fetchAll();
foreach ($results as $key => $result){
//$row is assigned to the whole fetchall result!
$row = $results->current();
//in this context $client cannot call a dependent rowset.
$client = $row->findDependentRowset('ORM_Post_Client','client');
}
MMc is correct in that you reference table definition was incorrect however your code has some issues as well. Maybe try something like:
$post = new ORM_Post();
$results = $post->fetchAll();
//unless your are going to use the 'key' for something you don't need it
foreach ($results as $result){
//you need each row object in order to call findDependentRowset in a one to many relationship.
$row = $post->find($result->id)->current();
//unless you have multiple rules set up for each table class pair you don't need to specify the rule.
$client = $row->findDependentRowset('ORM_Post_Client');
}
I use select queries as by following code:
$params = array(
'username' => 'root',
'password' => '',
'dbname' => 'mst2');
$db = Zend_Db::factory('pdo_mysql', $params);
$select = $db->select()
->from(array('dc' => 'delivery_center'))
->join(array('r' => 'region'), 'dc.region_id = r.region_id');
$stmt = $select->query();
$result = $stmt->fetchAll();
Here $db is the credentials of the database that I am using.But I have specified the credentials in application.ini already by following lines:
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = ''
resources.db.params.dbname = mst2
Now logically I should not provide these credentials again.But I have to use select queries.So how $db should be initialized without proving database credentials again??Thanks in advance.
Db resource is available by default and is initialized automatically whilst bootstraping.
If you want to get database adapter in your application you can get it as plugin resource from bootstrap:
$resource = $bootstrap->getPluginResource('db');
$db = $resource->getDbAdapter();
If you do not have reference to bootstrap you always can retrieve it from FrontController:
$front = Zend_Controller_Front::getInstance();
$bootstrap = $front->getParam('bootstrap');
You can use
Zend_Db::factory($zend_config_object->resources->db)
but i think if you have specified this in application.ini, then zend create db object for you automaticlly and you can get it through
Zend_Register and key "db".
we have this on Zend Manual:
$table = new Bugs();
$data = array(
'updated_on' => '2007-03-23',
'bug_status' => 'FIXED'
);
$where = $table->getAdapter()->quoteInto('bug_id = ?', 1234);
$table->update($data, $where);
Why do we need getAdapter and quoteInto again? I've read the manual but I don't understand.
What about the save() method, shouldn't we use it instead?
Regards,
MEM
save() is for when you are using Zend_Db_Table_Row if you are using Zend_Db_Table only, update is the method.
The code you've pasted needs to have the getAdapter and quoteInfo because $table is an instance of Bugs but not necessarily Zend_Db_Table_Row or Zend_Db_Table, therefore it isn't connected to the db.
I'm trying to do a group by using Zend framework. Here's my code:
$table = new TableClass();
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );
$results = $table->fetchAll ($select);
$result = $results[0];
$date = $result->date;
$column1 = $result->column1;
TableClass extends 'Zend_Db_Table_Abstract'.
I can see the query by looking at the mysql query log. The query is well formed - column1 is named in the query and the results look correct if I run the query in mysql workbench.
I cannot access the data in 'column1' - I always get this exception:
Uncaught exception 'Zend_Db_Table_Row_Exception' with message 'Specified column "column1" is not in the row'
I can however access the date column without issue.
I tried:
accessing the columns by array index:
$result[0]
but you get an exception (can't access the columns by index).
not using a column alias:
$select->from ("table", array("date", "sum(column1)"));
$column1 = $result["sum(column1)"];
but you get an exception (no such column "sum(column1)").
throwing in a Zend_Db_Expr:
"column1" => new Zend_Db_Expr ( "sum(column1)" )
but this doesn't help.
Some other examples I have seen suggest the use of the column names without aggregate functions, ie. "column1" instead of "sum(column1)" but that doesn't seem to me to be the answer - the query doesn't have any aggregate functions in it so mysql won't know what to do with it.
Any help appreciated.
Firstly, a quick tip for working with Zend_Db_Select (and by extension Zend_Db_Table_Select), you can view the generated SQL by invoking the toString method. It is vital to verify that your code generates the correct query before working with a result set:
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );
$sql = (string) $select; //Retrieve SQL as a string
Or simply
die($select); //print SQL
I wrote the following test script using your example and have no problems:
class Table extends Zend_Db_Table_Abstract
{
protected $_primary = 'id';
protected $_name = 'table';
}
$db = Zend_Db::factory('Pdo_Mysql', array(
'dbname' => 'test',
'username' => 'root',
'password' => '',
'host' => 'localhost'
));
$table = new Table($db);
$select = $table->select();
$select->from ($table, array("date", "column1" => new Zend_Db_Expr("sum(column1)")));
$select->group ( array ("date") );
$sql = (string) $select;
echo $sql;
$results = $table->fetchAll ($select);
$result = $results[0];
$date = $result->date;
$column1 = $result->column1;
echo '<br>' . $date . ': ' . $column1;
Use Zend_Debug::dump($result); to inspect data inside the Zend_Db_Table_Row if necessary.
In my case the SQL generated is as follows:
SELECT `table`.`date`, sum(column1) AS `column1` FROM `table` GROUP BY `date`