Is there no way to access a Model instance as an object (as opposed to as an array) within a Model method in CakePHP? As a super-simplified example, my instinct tells me it ought to be possible to do something like this:
Bird.php
...
public function specialName()
{
$name = $this->name;
return "Oh wow! It's ".$name;
}
If I call this method from my BirdController.php like so:
public function view($id) {
if (!$id) {
throw new NotFoundException(__('Invalid bird'));
}
$this->Bird->id = $id;
$this->set('results', $this->Bird->specialName());
}
... then it displays in the view file as "Oh wow! It's Bird" rather than "Oh wow! It's Freddy" (i.e. the name of the model, not the name of the model instance).
I've tried variations on this general approach, to no avail. It seems I must access the information via an array, like so:
Bird.php
...
public function specialName($id)
{
$data = $this->findById($id);
$name = $data['Bird']['name'];
return "Oh wow! It's ".$name;
}
This seems WAY over-complicated to me. What am I missing? Ultimately I want to be able to access dependent models in my model function, e.g. get all of the associated Bird->Subspecies. It seems like this would be much easier to do working with objects.
If you would have read the documentation about models you would know that Model::$name is the name of the model. There is also Model::alias which is the name of the model when it is accessed trough associations and the association is named different than the model name.
Cakes ORM does not return results as data objects, 3.0 will do that. Most easy way to return a specifc field right now is to do this in a model:
public function specialName($id) {
$this->id = $id;
return $this->field('name');
}
Also the "Oh wow..." should go to the view where you would echo the name that you set as $result.
If you want data objects, I know there is a plugin, a behaviour that will turn the result sets into data objects. Just google it.
Ultimately I want to be able to access dependent models in my model
function, e.g. get all of the associated Bird->Subspecies.
Did you read the book? See this section. With containable you can control what exactly you want to fetch from the associated models.
I recommend you to do the blog tutorial first to get an idea of the basics of how CakePHP works.
Related
I probably missed something really obvious, but have had no luck thus far. I have two related models, Messages and Users. I'm trying to append only the 'username' of the user who created the message when retrieving all messages. I am getting a fully serialized related user model however. I understand I could $hidden in my User model, but would like to avoid that.
In my Messages model, I've created a relationship
public function createdBy()
{
return $this->belongsTo('App\User', 'created_by');
}
Then I've added
protected $appends = ['username'];
Along with a custom attribute
public function getUsernameAttribute($value)
{
$username = null;
if ($this->createdBy){
$username = $this->createdBy->username;
}
return $username;
}
When I'm getting messages through another relationship such as
return $channel->messages()->orderBy('id','desc')->get();
I end up with the following response:
[{"id":97,"to_id":"12345","message":"This is the message content","created_at":"2017-02-25 08:58:22","created_by":{"id":1,"email":"REDACTED","name":"REDACTED","username":"myusername","created_at":"2016-09-26 16:00:00","created_by":null,"updated_at":"2017-02-20 00:33:06","updated_by":null},"updated_at":"2017-02-25 08:58:22","updated_by":null,"deleted_at":null,"username":"myusername"}, ...
What am I doing wrong, or is there a better way to accomplish what I'm trying to do?
I didn't realize I was able to hide the relationship in the original model. I ended up hiding the createdBy relationship in the Messages model.
protected $hidden = [
'createdBy'
];
I'm developing a system for a University here in Brazil. In this sytem I've got the following models:
- Country;
- State;
- City;
- University;
- Unit;
- Class;
Ok. and the relations are:
- State belongs to Country;
- City belongs to State;
- University belongs to Country (because, in my database, not every country has states registered to it and not every state has citys registered to it, so I could not demand from the user to register a University to a City);
- Unit belongsTo university;
- Class belongs to University (because not every University has Units registered to it);
Ok. I guess now I've set a good background for you guys to understand my situation. Now onto the question itself:
In the Views of my Model Class I wanna display the Country and (IF there are State City). And I may have the need to display such content in other Model views such as Unit and University.
But when I try to do that in my Class model I can only display the country_id. The foreign key in my university database table. And why is that, that is because my Class model belongs to University, so it's pretty easy to access my University's properties. However I do not wish to access the id of the Country, I want it's Name. And maybe in the future I might want other properties, who knows?
HOW DO I DO THAT? How do I access the properties of the Model Country when my Model Class has NO direct relation to it?
many thx hugs and kisses. Hope someone can help me with this one.
p.S:
I've managed a kinda loser solution: In my Class Controller I've done the following (so I can access variables of the Models Country, State and City):
In the View function I've loaded the Models for State and City (the country Model I can access by the relation Class->University->Country);
Then I used a find method to find the respective country, state and city for the Class in question I wanna display in view.ctp. The code follows:
public function view($id = null) {
$this->Class->id = $id;
$this->set('class', $this->Class->read());
$this->loadModel('State');
$this->loadModel('City');
$country = $this->Class->Universsity->Country->find('first', array('conditions' => array('Country.id' => $this->Class->data['University']['country_id']),));
$state = $this->State->find('first', array('conditions' => array('State.id' => $this->Class->data['University']['state_id']),));
$city = $this->City->find('first', array('conditions' => array('City.id' => $this->Class->data['University']['city_id']),));
$this->set('country',$country['Country']);$this->set('city',$city);
$this->set('state',$state);
}
And it kinda works...In my Wiew.ctp I get an array for Country data, and array for State data and an array for City data. And in the view I check to see if the state and city arrays are not length = 0 to display them and all...but I think there HAS to be a better way to do This.
P.P.S:
The other question is...what about the Index.ctp? How will I do that if I do not know which Class I'm working with? Will I have to have logic and find methods in the View? Isin't that just messing up the code?
Without posting your code, it's difficult to point you in the right direction. However, working on the assumption that you have your models configured correctly you should be able to do the following:
ClassController.php
public class ClassController extends AppController{
public $uses = array('Class');
public function view($id){
$class = $this->Class->find('first', array('conditions' => array('Class.id' => $id));
$this->set('class', $class);
}
}
view.ctp
<?php echo $class['Country']['name']?>
You may find however you will have to configure the recursive parameter of your class model so that CakePHP retrieves all the associated data. This can be done one of two ways:
Configure the recursive parameter within your Class model (see the documentation on how to do this). This sets the default value for recursive whenever you retrieve records from the database and you don't specify the attribute in your options.
Set the recurisve parameter within your find(...) method calls. I favor this one because it helps avoid placing a heavy load on the database when you don't need the data it retrieves.
For example, in your controller you could do the following:
public function view($id){
$class = $this->Class->find('first', array('conditions' => array('Class.id' => $id), 'recursive' => 3));
$this->set('class', $class);
}
Just a warning, don't set recursive to a value higher than you need, otherwise you may retrieve stuff that you don't particularly require. Use the debug() function to inspect what you're model is currently retrieving so you can make more of an informed decision:
debug($class);
I hope this is of some help!
The following is declared in model 'GradingPeriod':
class GradingPeriod extends AppModel {
public $belongsTo = array('AcademicYear' => array('className' => 'AcademicYear', 'foreignKey' => 'academic_year_id'));
...
public function getEnrolledSections(){
$this->recursive = 1;
debug($this->findById(21)); // Does **not** return AcademicYear
// model data when function is called
// from a different model.
debug($this->findById(21)); // **Does** return AcademicYear
// model data when function is called
// from a different model.
die();
}
}
When called from a controller or inside the GradingPeriod model, this works fine. The first 'find' call does return the GradingPeriod model's associated data (AcademicYear).
When called from a different model, the first 'find' call does not return the GradingPeriod model's associated data (AcademicYear). The second 'find' call does return the GradingPeriod model's associated data (AcademicYear).
class ReportCard extends AppModel {
public function callToGradingPeriod(){
$objGradingPeriod = ClassRegistry::init('GradingPeriod');
$objGradingPeriod->getEnrolledSections();
}
}
I have tried this with CakePHP 2.1.2 and 2.2.3 with the same results.
I know calling one model from another may be considered bad form, but why is this code behaving as it does? Thank you in advance for any assistance you can provide.
This is not really an answer as far as why it's working (or not) the way it is, but a suggestion for you and any future users trying something similar:
Don't EVER use recursive to get associated data. Set public $recursive = -1; in your AppModel and never look back. When you want related data, use CakePHP's Containable Behavior.
It might seem like recursive is your friend - or that it's "just easier", but I promise it will cause issues further down the road - either when you want more data, or just when you get more data in your database (memory issues/errors among other things). It's bad practice, and I believe they're even going to remove recursive all together in CakePHP 3+.
Trust me on this one - ditch recursive, and use contain() instead.
I'm using CakePHP 2.0.5 (but this isn't necessarily a cakephp specific question). I have a Coupon and a User model. Each time a user prints a coupon (proccessed by: Coupon Controller):
class CouponsController extends AppController {
public function printcoupon($id = null) {
// code
}
}
I want to save the information to a "coupons_printed" table (id/coupon_id/user_id/created). Should I create a new model for this, or should I just create a function inside of the Coupon model similar to (and call it in the controller each time that page is viewed)?:
class Coupon extends AppModel {
function insertIntoPrinted($id) {
$this->query("UPDATE coupons_printed SET .....");
}
}
Whatever you do, a raw SQL query is not the best way to go. Always use CakePHP methods if at all possible (and almost always it is possible).
You should put the insertIntoPrinted() function in the CouponsPrinted model (although, as a side note, PrintedCoupon would be a more natural way to name the model...) You can then add a HasMany relationship to the Coupon model ($hasMany = array( 'CouponsPrinted' )) and call the function in the CouponsController:
public function printcoupon($id = null) {
$this->Coupon->CouponsPrinted->insertIntoPrinted( $id );
}
CakePHP's model has a thing call association.
In your case, Coupon has a hasMany association with coupons_printed.
You can create a new model, or query using the association in the Coupon model, the generated queries will be the same, I believe.
Your CouponsController already depend on Coupon Model, so not creating another model is a better solution.
Today I've got a problem when I tried using following code to alter the model attribute in the controller
function userlist($trigger = 1)
{
if($trigger == 1)
{
$this->User->useTable = 'betausers'; //'betausers' is completely the same structure as table 'users'
}
$users = $this->User->find('all');
debug($users);
}
And the model file is
class User extends AppModel
{
var $name = "User";
//var $useTable = 'betausers';
function beforeFind() //only for debug
{
debug($this->useTable);
}
}
The debug message in the model showed the userTable attribute had been changed to betausers.And It was supposed to show all records in table betausers.However,I still got the data in the users,which quite confused me.And I hope someone can show me some directions to solve this problem.
Regards
Model::useTable is only consulted during model instantiation (see the API documentation for Model::__construct). If you want to change the model's table on the fly, you should use Model::setSource:
if ( $trigger == 1 ) {
$this->User->setSource('betausers');
}
The table to use is "fixed" when the model is loaded/instantiated. At that time a DB connection object is created, the table schema is being checked and a lot of other things happen. You can change that variable later all you want, Cake is not looking at it anymore after that point.
One model should be associated with one table, and that association shouldn't change during runtime. You'll need to make another model BetaUser and dynamically change the model you're using. Or rethink your database schema, a simple flag to distinguish beta users from regular users within the users table may be better than a whole new table.