开发者

cakephp: how to access another model, which has no association

开发者 https://www.devze.com 2023-03-20 12:23 出处:网络
I\'ve 3 tables: project, amenities and project_amenities. I add project form only, i want to add new amenities, which first added to amenities table and then project_amenities table.

I've 3 tables: project, amenities and project_amenities.

I add project form only, i want to add new amenities, which first added to amenities table and then project_amenities table.

So I defined these relations:

开发者_JAVA技巧

Project hasMany Amenities

Amenity belongsTo Project

I declared in projects_controller: var $uses = array('Amenity');

This gives error for my add action here

if (!empty($this->data)){

    $this->Project->create();

as

Notice (8): Undefined property: ProjectsController::$Project 
[APP\controllers\projects_controller.php, line 60]

edit Also, I cannot do:

$this->Amenity->create();
$insertData = array('name' => $this->data['Project']['Amenity'][$i]['name']);
$this->Amenity->save($insertData);


I wouldn't recommend using $uses = array() as it defies the purpose of having model relationships. Plus it adds a fair bit of overhead too.

You should use your model relationships where ever possible:

$this->Project->create();
$this->Project->Amenity->create();
$this->Model1->Model2->Model3->Model4->create();

If you want to use an unrelated model, you can do:

$this->loadModel('NewModelName');
$this->NewModelName->action();

Check out http://book.cakephp.org/view/1031/Saving-Your-Data and http://book.cakephp.org/view/992/loadModel


I would like to suggest you to use $this->loadModel('ModelName'); in the function where you needed. Then you can use the model as below

$this->ModelName->function();

By using $uses array it make available to entire controller. Which will affect your performance.


you must specify the project model in your $uses variable:

$uses = array('Project','Amenity');

but I'm curious why do you have three tables when you need one to many relationship?


Solution for :save for hasAndBelongsToMany

I created model: projects_amenity.php which has relation belongsTo project and amenity. model: projects has relation hasAndBelongsToMany with amenity controller: projects_amenities_controller

and in code:

$this->loadModel('ProjectsAmenity');
for($i = 0; $i< count($this->data['Project']['Amenity']);$i++)
{                       
    $this->Amenity->create();   

    $insertData = array('name' => $this->data['Project']['Amenity'][$i]['name']);
    $amenity = $this->Amenity->save($insertData);   

    $amenityid = $this->Amenity->getLastInsertID();

    $projectid = $this->Project->getLastInsertID();

    $this->ProjectsAmenity->create();           
    $data['AmenityArr']  = array('project_id' =>  $projectid,'amenity_id' => $amenityid );

    $this->ProjectsAmenity->save($data['AmenityArr']);  
}
0

精彩评论

暂无评论...
验证码 换一张
取 消