CakePHP find Queries with aliases SQLSTATE[42S22] Error - mysql

I'm having a weird problem with my relationships/aliases in CakePHP and now its preventing me from accessing my data correctly.
I have:
User hasMany CreatorModule (alias for Module)
User HABTM LearnerModule (alias for Module)
Module belongsTo Creator (alias for User)
Module HABTM Learner (alias for User)
And I'm trying to call:
$id = $this->Module->User->findByEmail($email);
$modules = $this->Module->findByUserId($id['User']['id']);
The queries that get generated aren't correct - the table-alias is wrong. I'm not sure which of the above is responsible but I get:
SELECT
`Creator`.`id`,
`Creator`.`email`,
`Creator`.`organization`,
`Creator`.`name`,
`Creator`.`password`,
`Creator`.`verified`,
`Creator`.`vcode`
FROM
`snurpdco_cake`.`users` AS `Creator`
WHERE
`User`.`email` = 'foo#example.com' # <--
LIMIT 1
I figured out that the error is that CakePHP should change 'User' in the WHERE clause to Creator, but doesn't, even if I use the alias. How do I complete this query correctly.
Further, as a related problem, I find that I can no longer use User in my model calls etc now that I have defined aliases. Is there a way around this?
EDIT: As requested, here is my model code defining the aliases:
class User extends AppModel {
public $name = 'User';
public $uses = 'users';
public $hasMany = array(
'OwnedModule' => array(
'className' => 'Module',
'foreignKey' => 'user_id',
'dependent' => true
));
public $hasAndBelongsToMany = array(
'LearnerModule' => array(
'className' => 'Module',
'joinTable' => 'modules_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'module_id',
'unique' => 'keepExisting',
));
//The rest of the Model
}
//Different file, condensed here for spacing
class Module extends AppModel {
public $name = 'Module';
public $belongsTo = array(
'Creator' => array(
'className' => 'User'));
public $hasAndBelongsToMany = array(
'Learner' => array(
'className' => 'User',
'joinTable' => 'modules_users',
'foreignKey' => 'module_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
));
//The rest of the Model
}

try
$id = $this->Module->Creator->find('first',
array('conditions' => array('Creator.email' => $email)
);
$modules = $this->Module->findByCreatorId($id['User']['id']);

Related

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');

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.

How use table in other database for "through" kohana ORM?

Sorry for my english, I'm from Ukraine.
I have next model
class Model_Search extends ORM
{
protected $_has_many = array(
'mp3s' => array(
'model' => 'Mp3',
'through' => 'searches_mp3s',
),
);
but table searches_mp3s in other database, for example 'db2'. How I can do relationship with through for my situation? Thank you
In pure SQL this should be database.table.field. And you must have user-connection who allow read from both databases.
I don't know, that kohana understand database.table notation...
You can try in your Model (ORM) class:
class Model_Search extends ORM
{
protected $_table_name = 'db1.search';
protected $_has_many = array(
'mp3s' => array(
'model' => 'Mp3',
'through' => 'db2.searches_mp3s',
),
);

Insert or update in laravel?

What would be the best way to set this query? i can't seem to find any documentation on an actual insert or update that works, I'm hoping to do it via the Eloquent model but can't seem to get it working
any help would be appreciated.
DB::table('questions')->insert([
'marital_status' => $request->marital_status,
'job_title' => $request->job_Title,
'industry' => $request->industry,
'occupation' => $request->occupation,
'paye' => $request->paye,
'self_employed' => $request->self_employed,
'child_benefit' => $request->child_benefit,
'work_home' => $request->work_home,
'own_transport' => $request->own_transport,
'company_vehicle' => $request->company_vehicle,
'annual_income' => $request->annual_income,
'pay_memberships' => $request->pay_memberships,
'income_benefits' => $request->income_benefits,
'printer' => $request->printer,
'contact' => $request->contact,
'share' => $request->share,
'terms' => $request->terms,
'user_id' => $user
]);
here is my Model for Questions
<?php
namespace App;
class Questions extends Model
{
protected $fillable = [
'marital_status',
'job_title',
'industry',
'occupation',
'paye',
'self_employed',
'child_benefit',
'work_home',
'own_transport',
'company_vehicle',
'annual_income',
'pay_memberships',
'income_benefits',
'printer',
'contact',
'share',
'terms',
'user_id'
];
public function users(){
return $this->hasOne('App\User');
}
}
Use Eloquent with mass assignment:
Question::updateOrCreate($request->all()->put('user_id', $user));
Or:
$question = Question::firstOrNew('some_id', $someId);
$question->fill($request->all()->put('user_id', $user))->save();
Don't forget to fill $fillable array with all properties you want to persist:
class Question extends Model
{
protected $fillable = [
'marital_status',
'job_title',
'industry',
'occupation',
'paye',
'self_employed',
'child_benefit',
'work_home',
'own_transport',
'company_vehicle',
'annual_income',
'pay_memberships',
'income_benefits',
'printer',
'contact',
'share',
'terms',
'user_id'
]
Update
If put() method doesn't work for some reason, try this:
$request->merge(['user_id' => $user]);
And then just use $request->all()
Or:
$requestData = $request->all();
$requestData['user_id'] = $user;
And then use $requestData

Cakephp 3.0 join in three table

I am trying to fetch the data from three table in cakephp 3.0
There is three table
1) size_category
2) sizes
3) sizerelations
Below is the file wise code
Model SizeCategoryTable.php
public function initialize(array $config)
{
parent::initialize($config);
$this->table('size_category');
$this->displayField('sizeCat_Id');
$this->primaryKey('sizeCat_Id');
// used to associate the table with user table (join)
$this->belongsTo('Users', [
'className' => 'Users',
'foreignKey' => 'CreatedBy',
'propertyName' => 'user'
]);
$this->hasMany(
'Sizerelations', [
'className' => 'Sizerelations',
'foreignKey' => 'Scat_Id',
'propertyName' => 'sizerelations'
]
);
}
Controller SizeCategoryController
public function index($id = null)
{
$customQuery = $this->SizeCategory->find('all', array(
'contain' => array(
'Users',
'Sizerelations' => array(
'Sizes' => array(
'fields' => array('id', 'Size_Code')
)
)
)
));
//debug();die();
$this->set('sizeCategory', $this->paginate($customQuery));
$this->set('_serialize', ['sizeCategory']);
}
I am greeting the error of Sizerelations is not associated with Sizes