CakePHP 3 is saying a table doesn't exist in another database when using an ORM query - cakephp-3.0

I have an application in CakePHP 3.5.13 which uses four different databases.
In my config/app.php I have configured two of these as follows:
'Datasources' => [
'default' => [ 'database' => 'sdb5_hub_subdb', ... ],
'db_orgs' => [ 'database' => 'dev_hub_subdb_orgs', ... ]
];
So this means there are 2 databases with the names sdb5_hub_subdb and dev_hub_subdb_orgs.
I'm attempting to do a query which does a join on a table in each database.
I have my Table entities configured as follows:
// src/Model/Table/TblListsSubstancesCommentsTable.php
public function initialize(array $config)
{
$this->belongsTo('Substances', [
'foreignKey' => 'substance_id',
'joinType' => 'INNER'
]);
}
public static function defaultConnectionName()
{
return 'db_orgs';
}
// src/Model/Table/SubstancesTable.php
public function initialize(array $config)
{
$this->belongsTo('TblListsSubstancesComments', [
'foreignKey' => 'substance_id'
]);
}
When I attempt to do the following with the ORM:
$query = $Substances->find()->select(['id' => 'Substances.id'])->distinct();
if ($this->request->getData('org_information')) {
$org_information = $this->request->getData('org_information');
$query = $query->matching('TblListsSubstancesComments', function ($q) use ($org_information) {
return $q->where(['TblListsSubstancesComments.comment LIKE' => '%'.$org_information.'%' ]);
});
}
It's producing an SQL error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sdb5_hub_subdb.tbl_lists_substances_comments' doesn't exist
I don't understand this because the table definitely exists. Furthermore my TblListsSubstancesCommentsTable.php has defaultConnectionName() in it to specify that it should use the db_orgs connection. So I assume it must know to go to the second database to load that table? It's like it's looking in the default database and not finding it, but I don't know why, because the Table entity is telling it where it needs to look.

Related

yii2 migration generates createTable instead of addColumn

I'm having trouble auto-creation migrations with bizley/yii2-migration-creator extensions on table updates. Initially, it works as expected with new tables:
<?php
use yii\db\Migration;
class m200122_110631_update_table_yii_urban_tourdate extends Migration
{
public function up()
{
$this->createTable('{{%urban_tourdate}}', [
'id' => $this->primaryKey(),
'name' => $this->string()->notNull(),
'time' => $this->dateTime(),
'duration' => $this->integer(),
'tour_id' => $this->integer(),
'tourguide_id' => $this->integer(),
'tourcourse_id' => $this->integer(),
'start_station_id' => $this->integer(),
'stop_station_id' => $this->integer(),
'status' => $this->integer(3)->notNull(),
'created_by' => $this->integer(),
'updated_by' => $this->integer(),
'created_at' => $this->integer(),
'updated_at' => $this->integer(),
]);
}
public function down()
{
$this->dropTable('{{%urban_tourdate}}');
}
}
Then after adding a column directly in database and creating another migration, I get a createTable statement as above (with the added column), which results in error (table already exists) when applying migration.
My expectation would have been to get only addColumn statement like this:
public function up()
{
$this->addColumn('urban_tourdate', 'position', $this->integer());
}
What am I doing wrong? Thanks!
You have to call
yii migration/update urban_tourdate
the second time (not create).

Associate tables from different database cakephp 3.0

I have two database with name default and default_history. And tables with name users and wafer_detail_history under default database and order_history under default_history database. want to associate Users table with OrderHistory table.
OrderHistoryTable :-
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('order_history');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('WaferDetailHistory', [
'foreignKey' => 'order_id'
]);
$this->belongsTo('Users', [
'foreignKey' => 'created_by',
'joinType' => 'INNER'
]);
}
i used this.
$connection = ConnectionManager::get('default_history');
$this->OrderHistory = TableRegistry::get('OrderHistory');
$this->OrderHistory->setConnection($connection);
$id = 37;
$order_history = $this->OrderHistory->get($id, ['contain' => ['Users']]);
but not able to succeed. getting this error:
Base table or view not found: 1146 Table 'default_history.users'
doesn't exist
I had the same problem few days ago,
You must had 'strategy' => 'select' in your BelongTo to join with the other database
$this->belongsTo('Users', [
'strategy' => 'select'
'foreignKey' => 'created_by',
'joinType' => 'INNER'
]);
Try this on the OrderHistoryTable.php File:
$this->setTable('default_history.order_history');

Validation rule unique requires at least 1 parameters. laravel 5.4

I've got problem with my laravel 5.4 I can't save the data
public function rules()
{
return [
'permission_id' => 'required|unique',
'name' => 'required',
'label' => 'required',
];
}
Error
Validation rule unique requires at least 1 parameters.
the unique rule need at least the name of ur database table.
ur rules function should be like this:
public function rules()
{
return [
'permission_id' => 'required|unique:db_table_name',
'name' => 'required',
'label' => 'required',
];
}
for more informations check laravel doc unique rule

CakePHP not respecting foreignKey name

I have an articles table with a column tagging_id that needs to reference the id column in a table called tracking_categories as a foreign key.
My Article.php file has the following:
class Article extends AppModel {
public $controllerPath = 'articles';
public $useTable = 'articles';
var $binds = array(
'TrackingCategory' => array(
'bindType' => 'belongsTo',
'className' => 'TrackingCategory',
'foreignKey' => 'tagging_id'
),
'Channel' => array(
'bindType' => 'belongsTo',
'className' => 'Channel',
'foreignKey' => 'channel_id'
)
);
My TrackingCategory.php looks like this:
class TrackingCategory extends AppModel {
public $useTable = 'tracking_categories';
I have the following in the AppModel which Article.php inherits:
function expects($binds, $reset = false) {
if (func_num_args() > 2 || !is_bool($reset)) {
throw new InvalidArgumentException('Did you mean to pass an
array of binds?');
}
if (!is_array($binds)) {
$binds = array($binds);
}
foreach ($binds as $bind) {
if (isset($this->binds[$bind])) {
$tmp = array($this->binds[$bind]['bindType'] => array($bind => $this->binds[$bind]));
$this->bindModel($tmp, $reset);
}
}
}
I am getting the following error:
Database Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Article.tracking_category_id' in 'field list'
It is still looking for the column named parsed via CakePHP's naming convention rather than the name that I explicitly set via the foreignKey value. What am I missing here?
The right syntax should be:
public $belongsTo = array(
'TrackingCategory' => array(
'className' => 'TrackingCategory',
'foreignKey' => 'tagging_id',
)
);
For more information, see CakePHP 2.x - Associations: Linking Models Together - belongsTo.

Authentication Component

I am using CakePHP for the first time. So, please, be patient with me:
I have a table called admin_users, when i try to add the Auth component in my AppController.php.
While executing, I always receive an error telling me that: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db_test.users' doesn't exist.
My table is called admin_users, so the error could be because the table should be always called "users" to work properly?
Here is my implementation in AppController.php:
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash');
$this->loadComponent('Auth',[
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'AdminUsers',
'action' => 'login'
]
]);
$this->Auth->allow(['display']);
}
and in AdminUsersController, the login function:
public function login()
{
if ($this->request->is('post')){
$adminUser = $this->Auth->identify();
if ($adminUser){
$this->Auth->setAdminUser($adminUser);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Your username or password is incorrect.');
}
}
Thank you.
Try this
In AppController.php:
function beforeFilter() {
$this->Auth->userModel = 'admin_users';
}