Zend_Db_Table Base table or view not found - mysql

I have taken over an application written with the use of the Zend MVC and Zend_Db_Table for DB access. I am trying to add a new table but get the error:
Base table or view not found: 1146 Table 'maa_agencies.contact' doesn't exist
However maa_agcencies.contact very much DOES exists and is in the same DB as the rest of the tables being accessed.
Here are my steps and code:
Step 1:
Create the Model Class
file: application/models/DbTable/Contact.php
class Model_DbTable_Contact extends Zend_Db_Table_Abstract
{
protected $_name = 'contact';
}
Step 2:
Instantiate the Class the same way it's done a dozen time in a controller (all other tables work)
file: application/modules/agency/controllers/IndexController.php (also step 3)
$agency_contact = new Model_DbTable_Contact();
Step 3:
Write my data to my new table ($store_contact is an assoc array with key = column name value = value)
$agency_contact->insert($store_contact);
Is there some caching function in Zend I am unaware of?
Some special thing I need to do to tell it I added a new table?
All documentation I have come across says this is all that is required, and as I state above the file I am trying to access my table through is already accessing 2 other tables in the same DB, in fact the line just above where I instantiate my Contact model is this statement that works fine:
$sm = new Model_DbTable_SentEmail();
The name space idea seems awesome! If this system wasn't some bastardization of the framework. Here is a currently working Model
/**
* #category Model_DbTable
* #package Model_DbTable_States
class Model_DbTable_States extends Zend_Db_Table_Abstract
{
protected $_name = 'state_list';
}
Is there some vodoo in the commenting perhaps, I am unable to find anywhere in the code where a namespace is registered at all.

Change your Class names of Model Directory. Add Prefix Application_
Example: Application_Model_DbTable_Contact

You forgot to add the namespace to your class
class Yournamespace_Model_DbTable_Contact extends Zend_Db_Table_Abstract
{
protected $_name = 'contact';
}
IN your application.ini ad this line
autoloaderNamespaces[] = "Yournamespace_"

Related

create rule class in dektrium module rbac in basic project yii2

I installed dektrium\user and dektrium\rbac\ modules for manage user and access control.Related tables and files installed completely and i can see several tabs in /user/admin path ( Users, Roles, Permissions, Rules, Create ) for work with modules.I can manage users perfectly(create user, reset password, edit,..). buy I can not create a rule.
I created a class in app\rbac\rules folder named AuthorRule :
<?php
namespace app\rbac\rules;
use yii\rbac\Rule;
use app\models\News;
/**
* Checks if authorID matches user passed via params
*/
class AuthorRule extends Rule
{
public $name = 'isAuthor';
/**
* #param string|int $user the user ID.
* #param Item $item the role or permission that this rule is associated with
* #param array $params parameters passed to ManagerInterface::checkAccess().
* #return bool a value indicating whether the rule permits the role or permission it is associated with.
*/
public function execute($user, $item, $params)
{
return isset($params['news']) ? $params['news']->createdBy == $user : false;
}
}
(I created news class with model,controler,views)
but when I entered name and class rule in my modules. Neither the data is logged nor the error message. I can't add the rest of the sections until I get into the rule.
I certainly hope the OP has solved their problem by now, but other people might encounter it.
First a remark: as described, the Save fails silently. This is because the form is submitted with Ajax (XHR). The error can be seen in the browser console.
This is the relevant part of the error message:
preg_match(): Compilation failed: invalid range in character class at offset 8
Due to the architecture of Yii 2, the actual regexp is a little tricky to find. It is in the model for Rules in yii2-rbac vendor/dektrium/yii2-rbac/models/Rule.php, line 86.
The original regexp is /^[\w][\w-.:]+[\w]$/
PHP 7.3 uses the PCRE2 library instead of the original PCRE, and the pattern above is wrong. The dash (-) needs to be escaped.
The full line should now be:
['name', 'match', 'pattern' => '/^[\w][\w\-.:]+[\w]$/'],
As the yii2-rbac package is abandoned, you can just modify the file. A more robust solution would be to override the Class.

Table name having additional underscores added

I have an API that grabs data from a table, serialises the data and then sends back via the service. The code is written using CakePHP using MySQL.
When I pass in the table name (such as RX_Scaled), an error is being returned that the table r_x_scaled can't be found (which don't surprise me, the table name in the database is rx_scaled).
My Model/Table for rx_scaled is defined like this
class rx_scaleds extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('rx_scaled');
}
With the Model/Entity
class rx_scaled extends Entity
{
}
My service API is set like this within the APIController.php file
public function getData($tablename, $id="", $filter = "-", $order = "-", $take = 0)
{
$the_table = $tablename;
$this->autoRender = false;
$table = TableRegistry::get($tablename);
$data = null;
switch (strtolower($the_table))
{
case "rx_scaled":
$data = $table->find();
echo $data;
break;
}
(this is truncated)
The odd thing is that this error does not occur in all tables.
I'm obviously not doing something correctly, but I'm not sure what
You named your table object rx_scaleds but then you pass RX_Scaled to the getData action
cake try not finding a Table Object named RX_Scaled try to inflect the name of the mysql table: so using cake's conventions RX_Scaled is mapped to r_x_scaled
So what can you do?
Use cake conventions
Name you table RxScaledsTable
class RxScaledsTable extends Table
Name you entity RxScaled
class RxScaled extends Entity
and pass the string 'RxScaled' to your action

Add WHERE condition to all SQL requests in Laravel

I'm creating an online tool for companies that each have a set of users in Laravel.
When a user is connected, he has a $connected_company_id variable
For every SELECT request (called by ::all(), find(), ...), i would like to add the condition: where company_id = $connected_company_id. I have found this post: laravel set an automatic where clause, but it doesn't work by overriding newQuery().
For every INSERT request, i would like to add the company_id.
Is this possible without changing my code inside all the controllers ?
I thought about extending Eloquent with customEloquent, and then make my models extend customEloquent, but I don't know how to write the code for customEloquent and if it could work.
Well, you could make use of the Eloquent Model Events. I assume you have the connected_company_id stored in the Session company_id
class BaseModel extends Eloquent{
public static function boot(){
parent::boot();
//Column to inject when inserting
static::creating(function ($obj){
$obj->company_id = Session::get('company_id');
});
//Column to inject when updating
static::updating(function ($obj){
$obj->company_id = Session::get('company_id');
});
}
}
You can extend the BaseModel class on all the models that you want the company_id to be inserted or updated. Take a look at Eloquent Model Events for more information.
The above code will automatically insert or update the company_id to the model that you extend the BaseModel to. When you do a Model::all() or Model::get(), you automatically get the company_id on that Model and you can also perform searches as you requested on Point `
Hope this helps.
well, you can just add the company id to the find query.
Model::where("company_id","=",$company_id):
Or you can create a scope:
class theModel extends Eloquent {
static $company_id;
static for_company($company_id){
self::company_id=$company_id;
return __CLASS__;
}
public function scopeCompany($query)
{
return $query->where('company_id', '=', self::company_id);
}
}
//And later
$scope=theModel::for_company($company_id);
$res=$scope::company->where(...);
Disclaimer: I haven't tried this. Just a solution I constructed. Let me know if this works. This will not work under PHP 5.3

Yii model: Dynamic table relations

Table.linkedIndex is related to LinkedIndex.ID. The value of the field LinkedIndex.TableName is either Linked1 or Linked2 and defines which of these tables is related to a row in Table.
Now i want to make a dynamical link with Yii models so that i can easily get from a Table row to the corresponding Linked1 or Linked2 row:
Table.linkedID = [LinkedIndex.TableName].ID
Example
Table values:
LinkedIndex values:
Now I should get the row from Linked2 where ID=2:
$model = Table::model()->findByPk(0);
$row = $model->linked;
Model
In the model Table, I tried to make the relation to the table with the name of the value of linkedIndex.TableName:
public function relations()
{
return array(
'linkedIndex' => array(self::HAS_ONE, 'LinkedIndex', array('ID' => 'linkedIndex')),
'linked' => array(
self::HAS_ONE,
'linkedIndex.TableName',
array('ID' => 'linkedID'),
)
)
}
But then I get the error:
include(linkedIndex.TableName.php) [function.include]: failed to open stream: No such file or directory
Is there any way to make a dynamic relation Table.linkedID -> [LinkedIndex.TableName].ID with Yii Models?
Per the Yii docs here:
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#relations-detail
I'd suggest using self::HAS_ONE instead (unless there can be multiple rows in LinkedIndex with the same ID - although from the looks of above, I doubt that's the case).
You can link tables together that have different keys by following the schema:
foreign_key => primary_key
In case you need to specify custom PK->FK association you can define it as array('fk'=>'pk'). For composite keys it will be array('fk_c1'=>'pk_с1','fk_c2'=>'pk_c2').
so in your case:
public function relations(){
return array(
'linkedIndex' => array(self::HAS_ONE, 'LinkedIndex', array('ID' => 'linkedIndex')),
);
}
where LinkedIndex is the class name for the LinkedIndex model (relative to your Table model - i.e. same folder. You could change that, of course) and array('ID' => 'linkedIndex') specifies the relationship as LinkedIndex.ID = Table.linkedIndex.
Edit
Looking at your updated example, I think you're misunderstanding how the relations function works. You're getting the error
include(linkedIndex.TableName.php) [function.include]: failed to open stream: No such file or directory
because you're trying to create another relation here:
'linked' => array(
self::BELONGS_TO,
'linkedIndex.TableName',
array('ID' => 'linkedID'),
)
This part: linkedIndex.TableName refers to a new model class linkedIndex.TableName, so Yii attempts to load that class' file linkedIndex.TableName.php and throws an error since it doesn't exist.
I think what you're looking for is to be able to access the value TableName within the table LinkedIndex, correct? If so, that's accessible from within the Table model via:
$this->linkedIndex->TableName
This is made possible by the relation we set up above. $this refers to the Table model, linkedIndex refers to the LinkedIndex relation we made above, and TableName is an attribute of that LinkedIndex model.
Edit 2
Per your comments, it looks like you're trying to make a more complex relationship. I'll be honest that this isn't really the way you should be using linking tables (ideally you should have a linking table between two tables, not a linking table that says which 3rd table to link to) but I'll try and answer your question as best as possible within Yii.
Ideally, this relationship should be made from within the LinkedIndex model, since that's where the relationship lies.
Since you're using the table name as the linking factor, you'll need to create a way to dynamically pass in the table you want to use after the record is found.
You can use the LinkedIndex model's afterFind function to create the secondary link after the model is created within Yii, and instantiate the new linked model there.
Something like this for your LinkedIndex model:
class LinkedIndex extends CActiveRecord{
public $linked;
public static function model($className = __CLASS__){
return parent::model($className);
}
public function tableName(){
return 'LinkedIndex';
}
public function afterFind(){
$this->linked = new Linked($this->TableName);
parent::afterFind();
}
//...etc.
}
The afterFind instantiates a new Linked model, and passes in the table name to use. That allows us to do something like this from within the Linked model:
class Linked extends CActiveRecord{
private $table_name;
public function __construct($table_name){
$this->table_name = $table_name;
}
public static function model($className = __CLASS__){
return parent::model($className);
}
public function tableName(){
return $this->table_name;
}
//...etc.
}
which is how we dynamically create a class with interchangeable table names. Of course, this fails of the classes need to have separate operations done per-method, but you could check what the table_name is and act accordingly (that's pretty janky, but would work).
All of this would result in being to access a property of the linked table via (from within the Table model):
$this->linkedIndex->linked->foo;
Because the value of LinkedIndex.TableName and Table.linkedID is needed to get the values, I moved the afterFind, suggested by M Sost, directly into the Table-Class and changed its content accordingly. No more need for a virtual model.
class Table extends CActiveRecord {
public $linked; // Needs to be public, to be accessible
// ...etc.
public function afterFind() {
$model = new $this->linkedIndex->TableName;
$this->linked = $model::model()->findByPk( $this->linkedID );
parent::afterFind();
}
// ...
}
Now I get the row from Linked2 where ID=2:
$model = Table::model()->findByPk(0);
$row = $model->linked;

kohana add column to inherit model

I was wondering how to work with kohana orm and inheritances.
Supose I have a model called Vehicle
$_table_columns with 5 columns
The lets supose I create another model called Car and I want to add 5 more columns to the model. How should I modify the parent $_table_columns variable or should I override it?
Thanks
I suppose you're looking for something like this protected $_table_columns = parent::_table_columns + array(...);. Unfortunatly PHP won't allow for this, so you will have to either override $_table_columns and list all 10 columns or override ORM reload_columns method like this:
public function reload_columns($force = FALSE)
{
$this->_table_columns = parent::_table_columns + array(...);
parent::reload_columns($force);
}