When Extending Zend_Db_Table_Abstract to Create a Join it Crashes MySQL - 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.

Related

Doctrine - delete all entities

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?

article get wrong categories in eloquent laravel 5.5

I got stuck in my code where I get wrong category in my article, for detail I will show my code,
Artikel model
class Artikel extends Model
{
protected $fillable = [
'judul', 'kutipan', 'slug', 'kategori_id','tag_id', 'isi', 'meta_keyword', 'meta_deskripsi', 'foto', 'status'
];
protected $table = 'artikel';
public function kategori(){
return $this->belongsTo('App\Kategori','id');
}
}
and this my Kategori model
protected $fillable = ['nama_kategori', 'slug'];
protected $table = 'kategori';
public function tag()
{
return $this->belongsTo('App\Tag','kategori_id');
}
public function artikel()
{
return $this->hasMany('App\Artikel','kategori_id');
}
and when I try this on php artisan tinker
Artikel::with('kategori')->where('slug','coba123')->get();
the result get wrong like this,
has anyone can help me? this make me confuse, I also have googling but still not change the result..
You are using the wrong column:
public function kategori(){
return $this->belongsTo('App\Kategori','kategori_id');
}

Mysql View in Laravel 5.2

This might be simple for someone. But for me I am totally lost. Can anyone give me a heads up for using Mysql View in Laravel 5. I've been searching for relevant post for a while but not a clue except:
DB::statement("Create View")
DB::statement("Drop View")
But this doesn't ring a bell. Any help, any clue, any guide is appreciated.
Thank in advance
My Scenario
I have an employee table with other tables that holds various attributes of the employee separately such as Appointment, posting,health, family etc etc. Most of these tables has one property Is_current to represent the current record of the employee. So whenever I want to display employee profile with latest record or retrieve some latest record from some of these tables, I don't want to retrieve from each an every table one by one. I just want to compile the latest record in a view and retrieve from it whenever I want.
I hope you understand my requirements and sorry for my bad english
I use views all the time for reporting purposes as I can create a denormalized View and then use the power of Models with Scopes and mutators. I wrote an article on how I manage MySQL Views.
# Create a new migration
php artisan make:migration create_employees_record_view
# Update the migration
<?php
use Illuminate\Database\Migrations\Migration;
class CreateEmployeesRecordView extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
\DB::statement("
CREATE VIEW employees_records
AS
SELECT
employees.emp_no,
employees.first_name,
employees.last_name,
employees.gender,
employees.hire_date,
employees.birth_date,
dept_emp.dept_no,
departments.dept_name,
mananger.emp_no AS manager_emp_no,
mananger.first_name AS manager_first_name,
mananger.last_name AS manager_last_name
FROM
employees
LEFT JOIN dept_emp ON employees.emp_no = dept_emp.emp_no
LEFT JOIN departments ON dept_emp.dept_no = departments.dept_no
LEFT JOIN dept_manager ON departments.dept_no = dept_manager.dept_no
LEFT JOIN employees mananger ON dept_manager.emp_no = mananger.emp_no;
");
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
}
}
# Run the migration
php artisan migrate
Managing it via Console Command
php artisan make:command CreateOrReplaceEmployeeRecordsViewCommand
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class CreateOrReplaceEmployeeRecordsViewCommand extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'view:CreateOrReplaceEmployeeRecordsView';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Create or Replace SQL View.';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
\DB::statement("
CREATE OR REPLACE VIEW employees_records
AS
SELECT
employees.emp_no,
employees.first_name,
employees.last_name,
employees.gender,
employees.hire_date,
employees.birth_date,
dept_emp.dept_no,
departments.dept_name,
mananger.emp_no AS manager_emp_no,
mananger.first_name AS manager_first_name,
mananger.last_name AS manager_last_name
FROM
employees
LEFT JOIN dept_emp ON employees.emp_no = dept_emp.emp_no
LEFT JOIN departments ON dept_emp.dept_no = departments.dept_no
LEFT JOIN dept_manager ON departments.dept_no = dept_manager.dept_no
LEFT JOIN employees mananger ON dept_manager.emp_no = mananger.emp_no;
");
}
}
Using Model To View
# Create a new model
php artisan make:model EmployeesRecord
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class EmployeesRecord extends Model
{
}
Test out the newly created Model
# For this we will be using tinker
php artisan tinker
>>> $e = \App\EmployeesRecord::first();
=> App\EmployeesRecord {#2885
emp_no: 10001,
first_name: "Georgi",
last_name: "Facello",
gender: "M",
hire_date: "1986-06-26",
birth_date: "1953-09-02",
dept_no: "d005",
dept_name: "Development",
manager_emp_no: 110511,
manager_first_name: "DeForest",
manager_last_name: "Hagimont",
}
>>> $e = \App\EmployeesRecord::where('emp_no', 10003)->first();
=> App\EmployeesRecord {#2896
emp_no: 10003,
first_name: "Parto",
last_name: "Bamford",
gender: "M",
hire_date: "1986-08-28",
birth_date: "1959-12-03",
dept_no: "d004",
dept_name: "Production",
manager_emp_no: 110303,
manager_first_name: "Krassimir",
manager_last_name: "Wegerle",
}
Ref - http://blog.tekz.io/laravel-eloquent-how-to-effectively-manage-sql-views/
To achieve this there is a good article here
I will show some code from the article .
Alter a base class like following:
public function save(array $options = [])
{
$this->toWriteMode();
try {
$saved = parent::save($options);
} catch (\Exception $e) {
$this->toReadMode();
throw $e;
}
$this->toReadMode();
return $saved;
}
protected $readOnly = [];
protected $readOnlyCache = [];
public function save(array $options = [])
{
$this->toWriteMode();
$this->cacheReadOnly();
try {
$saved = parent::save($options);
} catch (\Exception $e) {
$this->toReadMode();
throw $e;
}
$this->toReadMode();
$this->restoreReadOnly();
return $saved;
}
protected function cacheReadOnly()
{
$this->readOnlyCache = [];
foreach ($this->readOnly as $key) {
$value = $this->getAttributeValue($key);
$this->readOnlyCache[$key] = $value;
$this->__unset($key);
}
}
protected function restoreReadOnly()
{
foreach ($this->readOnlyCache as $key => $value) {
$this->setAttribute($key, $value);
}
}
Create Employee model as follows:
class Employee extends BaseModel
{
protected $table = 'employees';
protected $fillable = ['name'];
protected $guarded = ['id'];
public function people()
{
return $this->hasMany('Person');
}
}
Create EagerEmployee class as follows:
class EagerEmployee extends Employee
{
protected $readFrom = 'employeeView'; //Use your view name
protected $readOnly = ['person_ids'];
public function getPersonIdsAttribute($ids)
{
return $this->intArrayAttribute($ids);
}
}
This class will read its data from the view and we can save and retrieve it as normal. It will fetch read only attributes and they will be handled appropriately when saving.
That new intArrayAttribute() method just converts the comma delimited id string returned from the view into an array of integers.
We can use the Employee internally but if we need those extra read only attributes, say in an api response, we can use the EagerEmployee class.
P.S. The above code is copied from the given article and changed according to your needs.
Update:
Since old link to article is broken I'm adding a link to cached page of the site.
New Link to Article
Old Link to Article
'options' => [
\PDO::ATTR_EMULATE_PREPARES => true
]
Add Code to "config/database.php"
see picture below
Show Example

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;
}