CakePHP Access database table - cakephp

Suppose a table name of mysql database is 'admin' and controller name is 'userscontroller' and model name is 'user'.
How can I access the data from the table 'admin' in cakephp?
Please explain with code.

This is probably not the best solution but What I would do is make a new Model called 'Admin' specifically for that table, then in the UserController Call it, example:
In the UserController
$this->loadModel('Admin');
$this->Admin->find('all');
In the Admin Model
$useTable = 'admin';

Related

Larave database model relation between itself

I have some doubts about how to design a model whith a relation bewteen itself.
In my case, I have a users table with id and coach_id. All users has an id (obviously) but users with role Runner has also coach_id referred to an user with role Coach.
First step is how to create the key on laravel table migration and then, how to add correct relation in User model.
First, make sure that coach_id can be NULL:
$table->unsignedInteger('coach_id')->nullable();
Use unsignedBigInteger if model id use big integers.
Then define a foreign key:
$table->foreign('coach_id')
->references('id')
->on('users')
->onDelete('set null');
Use set null instead of cascade because you don't want delete related users when coach is deleted.
And set up one-to-many relation in User model:
public function coach() {
return $this->belongsTo(self::class);
}
From Laravel > 7 you can use shortcut in migration:
$table->foreignId('coach_id')
->nullable()
->constrained('users')
->onDelete('set null');

How does CakePHP 2 create a table?

I am having trouble understanding how the model class can create a table in the database.
If I wanted a table with fields users and password, wherein CakePHP do I define these fields? It seems like, in the examples I've seen, that these fields are validated in the model. But where are they defined or initialized?
Thanks.
CakePHP models don't create the database tables for you. They are a means of accessing existing tables that you have created. If you follow CakePHP's naming conventions the models just automatically know which tables they relate to; singular CamelCased model names relate to plural snake_cased tables.
To create your database tables you can either do this manually, or use CakePHP schemas to manage the database structure. There's also the excellent CakeDC migrations plugin for managing changes to the database structure.
CakePHP Schema management
CakeDC Migrations plugin
When a model is used in CakePHP it can determine the fields that belong to the model by running a SQL DESCRIBE query on the database table. This is done using the Model::schema() method. Cake caches the query results so that it doesn't need to keep querying the database for this.
Yes , sure , You can control database's table with its fields ,Model name should be the same of table name , in any controller you can load
$this->loadModel('SomeModel')
$mydata=$this->tableName->find('all');
$myuse =$this->set('myuse' , $mydata);
in your view , The name of view should be the same of your Controller's function name:
<h1> <?php echo $myuse['tableName']['fieldName]; ?></h1>
It not required to same name model as database table
like my table name is users and i create a model User
then you can define this table with User model in model > User.php
<?php
App::uses('AppModel', 'Model');
class User extends AppModel
{
public $name = 'User';
public $useTable = 'users';
public $primaryKey = 'id';
}

cakephp Model Relationships

I have an acl controlled cake application and specifically there are two tables I am having an issue with: 'users' and 'forms'. All of my tables have a 'created_by' field which links back to users giving me the user id of the records author. This is set on save within the forms model from Auth.
The issue I have is that each form record must be authorised by a user with a role of manager prior to being visible on site. I have therefore included a 'signoff_id' field which needs to relate back to the user table id.
In my Form model I have included the following
public $hasOne = array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'created_by'
),
'Signoff'=>array(
'className'=>'User',
'foreignKey'=>'signoff_id'
),
'Db',
'Identity'
);
This works ok with created_by and I get the correct info back from finds, but signoff_id is looking for a Signoff.signoff_id field (and trying to bring back all of the User table fields but substituting Signoff for User.
Any ideas gratefully received - I've tried the RT(F)M option but am no further forwards.
Finally joined the dots together ...
my Form model links back to the User model with a foreign key of 'id', and the User model links to Form with a foreign key of 'signoff_id'
Simple now I've sorted it.

Best way to bypass cakePHP's HABTM auto-magic?

My question is in relation this this answer.
https://stackoverflow.com/a/8773953/1297775
I have read at many places, what #deceze put as:
"To be quite honest, for any halfway complex application, relying on Cake's automagic handling of HABTM relationships can get quite fragile and hard to debug, so I always manage HABTM records myself."
Even the CakePHP book hints at it http://book.cakephp.org/2.0/en/models/saving-your-data.html#what-to-do-when-habtm-becomes-complicated
I want to ask, that when he says he 'manages' this HABTM records himself, does he...
1) Not create the HABTM relations in the models at all and create a model for the join table
OR
2) Create the HABTM relations in the models, but does not use it in the controller code by just using $this->FirstModel->JoinModel->saveAll($someData);
Thanks
Basically you need use a hasManyThrough relationship, which is essentially a HABTM setup manually which allows you to add extra data to the relationship (such as created/expiry dates). It's quite simple, you just need to create a model to join them and use the normal belongsTo and hasMany properties in the model, here is a simple user/membership/course setup:
class User extends AppModel {
public $hasMany = array('Membership');
}
class Course extends AppModel {
public $hasMany = array('Membership');
}
class Membership extends AppModel {
public $belongsTo = array('User', 'Course');
}
The only fields (at minimum) the memberships table needs is course_id and user_id.
You can now operate on the Membership model as a normal model, without Cake treating it as HABTM and using its auto-magic whenever you save records. You can also use cool counterCaches on the membership model to count how many users a course has etc.

CakePHP Associated Models available after save?

EDIT, I am rewriting the question for more clarity.
I have a "profile" model that has a belongs to relationship to a "user" model.
A certain user exists already. Later he creates a profile. The profile controller takes care of creating a new entry, but then needs to update a profile_id field as part of the associated user. I was under the impression that saveAll could take care of all the associations but it is not working?
What is the easiest/CakePHP standard way to do something like this? Thanks!
saveAll() creates new records. So you can't use it to update an already existing record in the Users table. As Anh Pham already mentioned, you've got your associations wrong. A Profile belongs to a User, and a User has one Profile. By having a profile_id field in your Users table, you're doing it the other way around.
So remove the profile_id field from the Users table, add a user_id field to the Profiles table, and update your model associations in user.php & profile.php.
To save a new Profile for an existing User, you can then either query the user id for the current User, or for example retrieve it through Auth, and add it manually to $this->data prior to calling the save() method of your Profile method.
You shouldn't have a profile_id field in the users table, you should have user_id field in profile table (the foreign key is similar to hasMany relationship). I'm surprised that the app still works http://book.cakephp.org/view/1041/hasOne
Also, I usually don't have hasOne relationship. If User hasOne Profile, then just include all fields in the profiles table into users table, unless there's some reason not to do it. But again, it's just my preference.

Resources