Suppose I have the classic Post model and I've created an Author model too.
I have some basic questions:
The Post object is automatically created whithin the PostsController?
In order to create an instance of Post whithin AuthorsController, is the only way with
$this->Post = ClassRegistry::init('Post');
Please notice that by doing " $this->Post " I assume the Post variable will be created in this line. Am I right ?
Thank you in advance!
Look into model associations. If your associations are set up properly, you will be able to do
$this->Author->Post
to access the Post model from the Authorscontroller. If the model was not related but you still needed to access it, you could do so using the $uses array.
In terms of your first question, you are correct. All of your controllers extend Appcontroller which imports the default cake Controller class found in /lib/. You can see on line 376 in the cakePHP controller file here that the model whose name is equal to the class name is loaded, after all of the models given in the $uses array are loaded.
All models in your uses array
You can access $this->MmodelName for all models declared in the uses property - If this property is not declared it defaults to the model corresponding to the controller - i.e. PostsContorller -> Post model.
Models declared in $uses as created/instanciated on first reference - i.e. they are lazily created.
Related
I have a problem with how to get the method name that was used in other models.
There is a list of models and some of them have used different method name on its relationship to other models.
For example, I have a model name of Member Rate Detail wherein it belongs to Member Rate model. The method that connects from Member Rate Detail to Member Rate is head() method.
Here is the sample code for head() method:
public function head()
{
return $this->belongsTo(MemberRate::class, 'member_rate_head_id')->withTrashed();
}
And for Customer Detail model it belongs to Customer model. And the connector method name that was used is group()
Here is the sample code for group():
public function group()
{
return $this->belongsTo(Customer::class, 'head_id', 'id')->withTrashed();
}
So the problem is I don't know if this model is using head() or group() or another method name.
Is there a Laravel Relationship concept way which can get a list or an array type of its foreign key's method used?
I'm expected to get the method name so that I can direct it to its instance class.
For example:
$memberRateDetail->getForeignMethod()->created_by;
**OR**
$customerDetail->getForeignMethod()->created_by;
Thank you so much!!!
No, there are not unless you declare them yourself.
Let's say you declare a method in your all your models where you declare the method for the class foreign relation. You can also implement it as an interface.
You can also just use code hinting if you have a good IDE, declaring a relation in PHP docs as * #property Collection head can help too.
I am new to Yii so I don't know much, but I can tell that Post is the name of my Model class.
The following code contains this $models = Post::model()->findAll($criteria);
You class Post is a CActiveRecord class and in this class there is a
model method
http://www.yiiframework.com/doc/api/1.1/CActiveRecord
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#model-detail
model() Returns the static model of the specified AR class. CActiveRecord
Returns the static model of the specified AR class. The model returned is a static instance of the AR class. It is provided for invoking class-level methods (something similar to static class methods.)
Hii this method is written in your model. In your case it is in Post model and if you want to know more than it written in your yiilite.php file under your framework folder.
For more info read this
http://www.yiiframew...rd#model-detail
The static model returned by model() contains the db schema meta data regarding the class.
So we need to call model() to get the static model when we call the functions like find() and findAll().
I am trying to create an observer for an Eloquent model to work as a logger for the changes on that model. I am not sure what parameters are passed to the observer's methods from the model. If the parameters don't include an instance of the updated model, is there another way around it without having to redefine the model class and override the needed methods?
class UserObserver{
public static function saved($user){
Activity::create([
"activity-name" => "save",
"user" => $user->id
]);
}
}
I found out that the model is actually passed, my mistake was not adding user property to the fillable array in the Activity model.
usually, I get an exception when my application tries to update fields that are not included in the fillable array, but this time I didn't. anybody knows why?
I am new to cakephp and trying to customise a cake application.
I have seen they are using models without having model class files in app/models folder
I think there is an automatic mapping from table to model
I am sharing some usefull lines of codes
public $uses = array('LinkEmperorCampaignDetail','Configuration','Article');
$this->paginate = array(
'conditions' => $condition,
'limit' => 10
);
$this->set('articles', $this->paginate('Article'));
As you have seen its importing Article model using $uses variable, there is a table "articles" in database, But there is no file Article.php in app/models. I have deleted cache folder and disabled caching.
I have checked if it is automatic, by creating a table "test" and used this code
$test=$this->test->find('all');;
var_dump($test);exit();
but getting this error Error: Call to a member function find() on a non-object
Please let me know how this is happening
Thanks,
Lajeesh
Change it to:
$test = $this->Test->find('all');
Also, please, check cakephp model and database conventions
Model files are optional
Cake will user an AppModel instance if there is no model file found:
CakePHP will dynamically create a model object for you if it cannot find a corresponding file in /app/Model.
As such a reference tothis->Article will be an instance of AppModel as the model is declared in the $uses variable but a model file doesn't exist.
That doesn't mean $this->RandomModel works
Referencing a random model, as seen in the question, will simply produce the following error:
Call to a member function find() on a non-object
That's to be expected because the controller knows nothing about the Test model from the code in the question.
The optional model file handling does not mean that you can reference any model by expecting it to exist as a Controller class property. $uses exists for the purpose of telling the controller which models it needs to know about. If a model is only needed in specific circumstances, loadModel exists for this purpose:
$this->loadModel('Test');
$stuff = $this->Test->find('all');
I have a controller/model for projects. so this controls the projects model, etc, etc. I have a homepage which is being controlled by the pages_controller. I want to show a list of projects on the homepage. Is it as easy as doing:
function index() {
$this->set('projects', $this->Project->find('all'));
}
I'm guessing not as I'm getting:
Undefined property: PagesController::$Project
Can someone steer me in the right direction please,
Jonesy
You must load every model in the controller class by variable $uses, for example:
var $uses = array('Project');
or in action use method
$this->loadModel('Project');
In my opinion the proper way to do this is add a function to your current model which instantiates the other model and returns the needed data.
Here's an example which returns data from the Project model in a model called Example and calls the data in the Example controller:
Using Project Model inside Example Model:
<?php
/* Example Model */
App::uses('Project', 'Model');
class Example extends AppModel {
public function allProjects() {
$projectModel = new Project();
$projects = $projectModel->find('all');
return $projects;
}
}
Returning that data in Example Controller
// once inside your correct view function just do:
$projects = $this->Example->allProjects();
$this->set('projects', $projects);
In the Example view
<?php
// Now assuming you're in the .ctp template associated with
// your view function which used: $projects = $this->Example->allProjects();
// you should be able to access the var: $projects
// For example:
print_r($projects['Project']);
Why is this "better" practice than loading both models into your controller? Well, the Project model is inherited by the Example model, so Project data now becomes part of the Example model scope. (What this means on the database side of things is the 2 tables are joined using SQL JOIN clauses).
Or as the manual says:
One of the most powerful features of CakePHP is the ability to link relational mapping provided by the model. In CakePHP, the links between models are handled through associations.
Defining relations between different objects in your application should be a natural process. For example: in a recipe database, a recipe may have many reviews, reviews have a single author, and authors may have many recipes. Defining the way these relations work allows you to access your data in an intuitive and powerful way. (source)
For me it's more reasonable to use requestAction. This way the logic is wrapped in the controller.
In example:
//in your controller Projects:
class ProjectsController extends AppController {
function dashboard(){
$this->set('projects', $this->Project->find('all'));
}
$this->render('dashboard');
}
Bear in mind that you need to create dashboard.ctp in /app/views/projects of course.
In the Page's dashboard view (probably /app/views/pages/dashboard.ctp) add:
echo $this->requestAction(array('controller'=>'projects', 'action'=>'dashboard'));
This way the logic will remain in the project's controller. Of course you can request /projects/index, but the handling of the pagination will be more complicated.
more about requestAction(). but bear in mind that you need to use it carefully. It could slow down your application.