Cakephp: How to get table data without creating Models/Controllers? - cakephp

My doubt is, I had few tables named client1,client2,client3 etc., I need to get the data of each client in single controller without creating any model/controller for each table. Can any one explain how to get those values.

You can use dynamic models
app/client_model.php
<?php
class ClientModel extends Model {
var $name = 'Client';
var $alias = 'Client';
function __construct($table) {
$this->useTable = $table;
parent::__construct();
}
}
?>
And Use like this for client1 table
App::import('model','Client');
$client = new ClientModel('client1');
$client->find('all');

You Can do it by firing normal mysql queries selecting table and fetching values
in controller as we do in core php.

Related

access model class inside entity class of other model

I am using CakePHP 3.4+
I have written an application with multi level membership.
The Pro members will have benefit to view short url for external links which when shared will record the visit count to that url.
The original url is stored in PostVideos table for all user.
I have created a table to store uniuqe keys for short urls inside short_video_post_urls with columns
+----+---------------+------------+-------------+
| id | post_video_id | unique_key | visit_count |
+----+---------------+------------+-------------+
Since, count of Pro members will be low than normal users, I don't want to generate unique_key entry in short_video_post_urls because It will flood database with useless records.
So, what I want is to generate them dynamically and store them for PRO members only
Now, in template file I'm using $postVideo->video_url to display original video url from post_videos table.
Question
What I want is to tweak video_url entity call which will check for
Membership level of logged in user
If member is pro
check if unique key exists in ShortVideoPostUrls model for the url requested
If no record exists, then create a unique_key in ShortVideoPostUrls
return the new url with unique_key
But for that I need to access logged_in user data in the entity class.
What I tried?
class PostVideoLog extends Entity
{
/*
* ----
* ----
*/
protected function _getVideoUrl()
{
$user = $this->Users->get($this->Auth->user('id'), [
'contain' => [
'MembershipLevels'
]
]);
if ($user) {
if (strtolower($user->membership_level->title) === 'pro') {
/**
* check if unique_key exists for this request
*/
$checkShortUrl = $this->ShortVideoPostUrls->find()
->where(['post_video_log_id' => $this->_properties['id']])
->first();
if ($checkShortUrl) {
return $this->_generateUrl($checkShortUrl->unique_key);
}
/**
* create new record
*/
$unique_key_generator = new Hashids(UNIQUE_SHORT_URL_SALT, 4);
$unique_key = $unique_key_generator->encode($this->_properties['id']);
$newShortUrl = $this->ShortVideoPostUrls->newEntity();
$newShortUrl = $this->ShortVideoPostUrls->patchEntity($newShortUrl, [
'unique_key' => $unique_key,
'post_video_log_id' => $this->_properties['id']
]);
if ($this->ShortVideoPostUrls->save($newShortUrl)) {
return $this->_generateUrl($unique_key);
}
}
}
return $this->_properties['video_url'];
}
private function _generateUrl($unique_key)
{
$base_url = Router::url('/', true);
return $base_url . '/u/' . $unique_key;
}
}
I'm not sure, whether my approach is right or wrong.
To load Users model and other models I'm using in above function requires to use
$this->loadModel('Users');
But, loadModel seems not to be working here.
What is other approach to do this? Or how to load external model and Auth component in Entity class?
Edit 2
Is there any better alternative to do what I want without entity? or simply some way to call function from template on each entity?
Ex.
$postVideo->video_url()
To load other model inside entity You can use TableRegistry class
use Cake\ORM\TableRegistry;
class MyModel extends Entity {
protected function _getVideoUrl() {
$table = TableRegistry::get('Users');
$users = $table->find('all')->toArray();
}
}
I think its not the best idea to use Auth component in model - I dont know how to do this "properly", but all session data (including auth data) is still available in $_SESSION array

CakePHP: create temporary table and use it

I'm trying to create a temporary table within CakePHP 2.x, but I always receive the message "Error: Call to a member function query() on a non-object".
I did some research and found a solution, but this one is not working for me: Create temporary table in CakePHP and load it as a Model
EDIT:
The following code now produces a different error: "Error: Table devices_cls for model DevicesCl was not found in datasource default."
Here is my code:
class DevicesController extends AppController {
public $uses = array('Device','Client');
public function index(){
$conditions = array();
$tmpModel = 'DevicesCl';
$tmpTable = 'devices_cls';
$this->loadModel('DevicesCl');
$this->DevicesCl->query("CREATE TEMPORARY TABLE IF NOT EXISTS devices_cls AS (SELECT uuid,ownerUuid,status,os,imei,updatedOn,msisdn,model FROM device)" );
As I'm quite new to CakePHP, do I need to add an additional model class? I don't think so, as this should be handled by the temporary table - right?
Thanks for your support!
class DevicesController extends AppController {
public $uses = array('Device','Client');
public function index(){
$conditions = array();
$tmpModel = 'DevicesCl';
$tmpTable = 'devices_cls';
$this->loadModel('DevicesCl');
$this->DevicesCl->useTable=false;
$this->DevicesCl->query("CREATE TEMPORARY TABLE IF NOT EXISTS devices_cls AS (SELECT uuid,ownerUuid,status,os,imei,updatedOn,msisdn,model FROM device)" );
$this->DevicesCl->useTable = $tmpTable;
The problem is that the Model "DevicesCl" does not exist yet.
in your example on the link : the Model exist
so if you change
$this->DevicesCl->query(...)
to
$this->Model->query(...)
But i don t see why you need a functionnality like that... i think there are surely best solutions no ?
In Cakephp 3, you can do the following:
Model/Table/MyTempTable.php
<?php
// ......
class MyTempTable extends Table{
public function initDownload(){
$connection = ConnectionManager::get('default');
$connection->execute('CREATE TEMPORARY TABLE temptemp as (select * from refernece_db)');
// Do your thing
}
}
// When use the temp table, first should do:
$this->MyTempTable->initDownload();
// Then, can use Cakephp3 Table syntax normally as if it is a normal table

define model association without the second model

Is there a way in CakePHP 1.3 to define a model association without having a model for the associated table? For example:
<?php
class SomeModel extends AppModel
{
var $useTable = 'some_table';
var $belongsTo = array(
'AnotherModel' => array(
// association data here
)
);
}
?>
Where AnotherModel doesn't actually have a model file. I just want to define the table that model would use and the association details. Is this possible?
Quick answer is: It should be fine. Have you tried it? Worse case scenario is it won't work without the file, so just add the model file. It takes all of two seconds:
<?php
class AnotherModel extends AppModel {
var $name = 'AnotherModel';
}
?>
Done!
UPDATE
If you follow cake convention on the naming of tables, you should be able to reference the table using the appropriate name without the model file. For example:
my_models = MyModel
your_models = YourModel
model_tables = TableModel
However, if you have a table that does not follow convention, you must create a model file that defines $useTable to indicate which table it relates to:
some_table = model file: SomeTable where $useTable = 'some_table';
another_model = model file: CustomModel where $userTable = 'anotherModel';
There is no other way around it. CakePHP is not magic. It needs to know what table is being referenced. Unless you are doing joins. Then in the join you can reference the table.

CakePHP doesn't load model

I'm new to cakePhp development. I've stuck on following problem:
I've made few models, controllers and views - it works great. The problem is that after production, I have to made new table(Transactionaltemp table and corresponding model and controller ) in the db that logically is "connected" to other tables, but technically does not needs to - for ex. it holds temporary info on user_id, time, ip and similar. So, other tables doesn't need to be directly connected to that.
The problem is when I try (in some other controller than transactionaltemps_controller):
$this->loadModel('Transactionaltemp');
I get error - the model is not found (it is true because the model is missing in the cache). Interesting enough transactionaltempls_controller is in the cache (in the cake_controllers_list file).
I tried following stuff to resolve the problem:
clear cache
disable cache
tried using uses={..} code in the controller that I would like to use mymodels_controller
tried using init('Transactionaltemp')
with no success. Here is corresponding code:
The model:
<?php
class Transactionaltemp extends AppModel
{
var $name = 'Transactionaltemp';
function beforeSave() {
return true;
}
}
?>
The controller:
<?php
class TransactionaltempsController extends AppController
{
var $name = 'Transactionaltemps';
var $scaffold;
}
?>
I'll very grateful to any help!!!
App:Import('Model','Transactionaltemp');
$this->Transactionaltemp= new Transactionaltemp;
I hope this may work
If you are connecting to a table name with different name than your model, you must specify the table name in it:
<?php
class Transactionaltemp extends AppModel
{
var $uses = 'Transactional';
var $name = 'Transactionaltemp';
function beforeSave() {
return true;
}
}
Try
App::Import('Model', 'YourModelName');
in your controller (or where you want).

CakePHP requiring a database table

I intended to create a controller that handles a contact page. I created the controller ContactsController. The problem is that it is asking for a table with the same name:
Missing Database Table
Error: Database table
username_contacts for model Contact
was not found.
Notice: If you want to customize this
error message, create
app/views/errors/missing_table.ctp
Do I really need to create a table with no data for this?
This is my controller code:
<?php
class ContactsController extends AppController {
var $name = 'Contacts';
function index($id = null)
{
$this->set('page', ClassRegistry::init('Page')->findByShortname($id));
}
}
var $name = 'Contacts';
var $uses = array();
not to be that guy, but this is documented well.
http://book.cakephp.org
You might want to create the model anyway as you'll almost certainly find you need to do some database type stuff. It doesn't need to use a db_table:
class ModelWithoutTable extends AppModel
{
var $useTable = false;
}
Think "fat model - thin controller"

Resources