Doctrine - delete all entities - mysql

I have problem with deleting all rows in database. I can't find out how to do it. I'm using Symfony and Doctrine. Somewhere I read, that it isn't possible "normal" way, but I can do it by DQL (createQuery), but I don't know syntax.
public function resetDatabase(EntityManagerInterface $em)
{
$query = $em->createQuery('DELETE ???');
$query->execute();
return new Response('', Response::HTTP_OK);
}

public function resetDatabase(EntityManagerInterface $em)
{
$query = $em->createQuery(
'DELETE FROM App\Entity\YourEntity e WHERE e.age > :ageparameter'
)->setParameter('ageparameter', 10)->execute();
return new Response('', Response::HTTP_OK);
}

Ou... I have find out, how to do it.
/**
* #Route("/resetdatabase")
*/
public function resetDatabase(EntityManagerInterface $em)
{
$repository = $em->getRepository(MoneyDatabase::class);
$entities = $repository->findAll();
foreach ($entities as $entity) {
$em->remove($entity);
}
$em->flush();
return new Response('', Response::HTTP_OK);
}
But sometimes it must run twice, because somehow after 30 seconds entities return (but there are only compulsory columns, others are null). And after second run it disappear completely. It's strange, that it does only sometimes. Why it does at all?

Related

Method chainning for join table with pagination on CI 3

I create a core class named MY_Model that extends CI_Model. In this class, I create a method chaining to get all record with pagination like this :
// Take record with paging.
public function get_all_paged()
{
// get argument that passed
$args = func_get_args();
// get_all_paged($offset)
if (count($args) < 2) {
$this->get_real_offset($args[0]);
$this->db->limit($this->_per_page, $this->_offset);
}
// get_all_paged(array('status' => '1'), $offset)
else {
$this->get_real_offset($args[1]);
$this->db->where($args[0])->limit($this->_per_page, $this->_offset);
}
// return all record
return $this->db->get($this->_tabel)->result();
}
So , I just used like this on my controller,
for example
public function index($offset = NULL) {
$karyawan = $this->karyawan->get_all_paged($offset); //get all
}
I am realy confuse to get all record using join, I know join in CI like this :
public function get_all_karyawan() {
$this->db->select('tb_1 , tb_2');
$this->db->from('tb_1');
$this->db->join('tb_2', "where");
$query = $this->db->get();
return $query->result();
}
How to make it into chain in MY_Model?
Any help it so appreciated ...
The good thing in query builder, you can chain your db methods, till get(). So you can define, selects, where queries, limits in different ways.
For example:
public function category($category)
{
$this->db->where('category_id', $category);
return $this;
}
public function get_posts()
{
return $this->db->get('posts')->result();
}
And you can get all posts:
$this->model->get_posts();
Or by category:
$this->model->category(2)->get_posts();
So upon this, in your model:
public function get_all_karyawan() {
$this->db->select('tb_1 , tb_2');
$this->db->join('tb_1', "where");
// Here you make able to chain the method with this
return $this;
}
In your controller:
public function index($offset = NULL) {
$karyawan = $this->karyawan->get_all_karyawan()->get_all_paged($offset);
}

Issue with a Table Model

I've been having a problem with a table model recently and I can't really explain why this happens. I want to select everything from a table and return it in a descending order. But when I try to display it nothing shows up:
Code:
<?php
//Will be used at a later date
namespace Blog\Model\Table;
use Zend\Db\TableGateway\TableGateway;
class Blog extends TableGateway
{
public function __construct($adapter)
{
parent::__construct('posts', $adapter);
}
public function displayPosts()
{
$adapter = $this->getAdapter();
$result = $adapter->query('SELECT * FROM `posts` ORDER BY `date_added` DESC');
return $result;
}
}
Result:
But when I add an $id argument it shows the data:
Code:
<?php
//Will be used at a later date
namespace Blog\Model\Table;
use Zend\Db\TableGateway\TableGateway;
class Blog extends TableGateway
{
public function __construct($adapter)
{
parent::__construct('posts', $adapter);
}
public function displayPosts($id = 6)
{
$adapter = $this->getAdapter();
$result = $adapter->query('SELECT * FROM `posts` WHERE `post_id` = ?', array($id));
return $result;
}
}
Result:
It's weird that it works with an argument and not without, any ideas?
You needed to order it by post_id
public function displayPosts()
{
$adapter = $this->getAdapter();
$result = $adapter->query('SELECT * FROM `posts`')->order(array('post_id' => 'DESC'));
return $result;
}

CodeIgniter active records' problems calling multiple stored procedures

class Registration_model extends CI_Model {
function __construct() {
parent::__construct();
}
function check_email_availability($email)
{
$sql = "CALL proc_1301('$email');";
$query = $this->db->query($sql) or die(mysql_error());
return $query->row_array();
}
function check_username_availability($username)
{
$sqlt = "CALL proc_1303('$username');";
$query = $this->db->query($sqlt) or die(mysql_error());
return $query->row_array();
}
function process_registration($username, $email, $password)
{
$sql = "CALL `proc_1302`('$username', '$email', '$password');";
$query = $this->db->query($sql) or die(mysql_error());
return $query->result_array();
}
this is my controller code which calls three functions from model one by one:
$emailCheckRes = $this->Registration_model->check_email_availability($email);
$usernameCheckRes = $this->Registration_model->check_username_availability($username);
$this->data['regRes'] = $this->Registration_model->process_registration($username, $email, $password);
my problem is when i run only one function it runs successfully but when i run two of them or all three it shows blank page... any idea why ???
SOLUTION
So finally the only solution we got for my own problem is :
/* ADD THIS FUNCTION IN SYSTEM/DATABASE/DB_ACTIVE_REC */
/* USAGE $this->db->freeDBResource($this->db->conn_id); */
function freeDBResource($dbh){
while(mysqli_next_result($dbh)){
if($l_result = mysqli_store_result($dbh)){
mysqli_free_result($l_result);
}
}
}
The problem is related to CodeIgniter's active recors and multiple database stored procedure calling.
First of all check that dbdriver parameter (application/config/database.php) is set to mysqli.
Then, as described in "Calling a stored procedure from CodeIgniter's Active Record class" question on StackOverflow, adding to system/database/DB_active_rec.php the following function:
function freeDBResource($dbh){
while(mysqli_next_result($dbh)){
if($l_result = mysqli_store_result($dbh)){
mysqli_free_result($l_result);
}
}
}
..And in your controller use:
$this->db->freeDBResource($this->db->conn_id);
after any stored procedure calling.
Model and Controller seems to be ok.
If you try a model like:
class Test_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function a($a_input)
{
return($a_input.': a');
}
function b($b_input)
{
return($b_input.': b');
}
}
...And call it functions from a controller like this:
$this->load->model('Test_model');
$a_result = $this->Test_model->a('aaa');
$b_result = $this->Test_model->b('bbb');
echo($a_result.'<br />'.$b_result);
You can see multiple function calling working fine.
Are you sure you can execute any of three function in model correctly, if you call only one?
If yes, maybe the problem can be find in your stored procedures... Can you try to execute a normal query instead of stored procedures, in model functions? For debug your problem, check also in your /application/config/database.php if db_debug is set to TRUE.

Getting the last User ID in Zend Framework

Using MySQL query browser, I manually made a table called users and input some date in the fields. I set the primary key to id and set it to auto increment. There are 3 rows, the highest id is 3.
I then made the following class in the method directory to call upon the data in the table etc.
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
{
protected $_name = 'user';
public function getLatestUserId()
{
$id = $this->getAdapter()->lastInsertId();
return $id;
}
}
In the controller I do the following which gets the value generated by the method and lets the view access it:
$usersDbModel = new Application_Model_DbTable_User();
$lastUserId = $usersDbModel->getLatestUserId();
$this->view->lastUserId = $lastUserId;
In the view I then echo it to display it to the user:
echo $this->lastUserId;
However, even though my last id in the users table is 3. It displays 0.
I have also tried:
public function getLatestUserId()
{
$sql = 'SELECT max(id) FROM user';
$query = $this->query($sql);
$result = $query->fetchAll();
return $result;
}
But this just throws out a server error.
What have I done wrong?
Am I missing something?
Is there another way of doing this?
The answer was:
$sql = 'SELECT max(id) FROM user';
$query = $this->getAdapter()->query($sql);
$result = $query->fetchAll();
return $result[0]['max(id)'];
If you queried like "SELECT id FROM USERS SORT BY id DESC LIMIT 0,1"
You would get nothing but the id of the newest user, no?
if you use a select statement like
SELECT max(id) FROM USERS;
If you haven't tried having a function in the controller try something like this.
class IndexController extends Zend_Controller_Action {
public function init() {
}
public function indexAction() {
}
public function getLatestUserId()
{
$bootstrap = $this->getInvokeArg('bootstrap');
$resource = $bootstrap->getPluginResource('db');
$db = $resource->getDbAdapter();
$sqlrequest = "select max(id) as Idmax from user";
$rows = $db->fetchAll($sqlrequest);
foreach ($rows as $row)
echo $maxId = $row['Idmax'];
return $maxId;
}
}
and your bootstrap file would look something like
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initConfig()
{
$config = new Zend_Config($this->getOptions());
Zend_Registry::set('config', $config);
return $config;
}
}
Hopefully something like that works, hope it helped
The problem is that Mysql doesn't really support lastInsertId() it will in some cases return the last id of an auto incrementing primary key.
Several solutions have been presented here and most will return the last id of the primary key, which may or may not be what you really need.
This method will also do the same using the select() object.
public function getlastInsertId(){
$select = $this->select();
$select->from($this->_name, "id");
$select->order('id DESC');
$select->limit(0, 1);
$result = $this->fetchAll($select)->current();
return $result->id;
}
I think that over time you may find these kinds of methods unreliable if what you're really after is the last id you inserted. Over time as records are added and deleted the database may or may not fill in vacant id's depending on which database you are currently using and how that database is set up.
In most cases we need the id of the last item inserted very soon after inserting it, usually to update a view script. In this instance I usually just make the whole row object part of the return.
Here is an example of what I mean:
/**this method will save or update a record depending on data present in the array*/
public function saveUser(array $data) {
/**cast data array as std object for convience*/
$dataObject = (object) $data;
/**if id exists as array and has a non null value*/
if (array_key_exists('id', $data) && isset($data['id'])) {
/**find row if updating*/
$row = $this->find($dataObject->id)->current();
} else {
/**create new row*/
$row = $this->createRow();
}
$row->first_name = $dataObject->first_name;
$row->last_name = $dataObject->last_name;
$row->email = $dataObject->email;
/**save or update row*/
$row->save();
/**return the $row you just built or you can return $result = $row->save(); and get*/
/** just the primary key. Save() will throw an exception if table is marked read only*/
return $row;
}

When Extending Zend_Db_Table_Abstract to Create a Join it Crashes MySQL

I want to understand why this works perfect with out a problem.
$this->db = Zend_Db_Table_Abstract::getDefaultAdapter();
public function getMessages()
{
$select = $this->db->select();
$select
->from('Mail_Text', '*')
->join(
array('Mail' => 'Mail'),
'Mail.id = Mail_Text.parent_id', '*'
);
return $this->db->fetchAll($select);
}
Now if I do this by extending Zend_Db_Table_Abstract
class Mail_Model_Text extends Zend_Db_Table_Abstract
{
protected $_name = 'Mail_Text';
public function fetchMessges(){
$select = $this->select();
$select->setIntegrityCheck(false)
->from($this->_name, '*')
->join(
array('Mail' => 'Mail'),
'Mail.id = Mail_Text.parent_id', '*'
);
return $this->fetchAll($select);
}
}
This crashes MySql I wanted to keep the code separate but I can join theses tables. All the Single select and updates query's work perfect. I have research all over the net and can't seem to find the solution to this puzzle. Any Help to his would be great Thanks in advance.
You don't need the from() statement or need to alias the table to the same name:
class Mail_Model_Text extends Zend_Db_Table_Abstract
{
protected $_name = 'Mail_Text';
public function fetchMessges()
{
$select = $this->select();
$select->setIntegrityCheck(false)
->join('Mail', 'Mail.id = Mail_Text.parent_id');
return $this->fetchAll($select);
}
}
Also, ensure that you have correctly indexed your tables.