Retrieve linked data from different tables in CakePHP

Asked 2 years ago, Updated 2 years ago, 45 views

RoomsController

public function index(){
    $this->Room->recursive=0;
    $this->Prg->commonProcess();
    $this->paginate=array(
        'Room' = >
    array(
        'conditions' = > array(
            $this->Room->parseCriteria ($this->passedArgs),
        )
    ));
    $this->set('rooms', $this->paginate());
}

debug($rooms);

array(
(int) 0 = > array(
    'Room' = > array(
        'id' = > '0001',
        'room_id' = > '1234',
        'name' = > 'hogehoge',
        'area_id' = > 'tko1234',
    )
),
(int) 1 = > array(
    'Room' = > array(
        'id' = > '0002',
        'room_id' = > '1235',
        'name' = > 'fugafuga',
        'area_id' = > 'osk1234',
    )
)

If so,

<?php foreach($rooms as$roos):?>
$rooms['Room']['area_id'];
<?php endforeach;?>

For 'tko1234', 'osk1234', how do I output the area names 'Tokyo' and 'Osaka', respectively, in conjunction with the Area table we have prepared?

Area Table

array(
(int) 0 = > array(
    'Area' = > array(
        'id' = > 'tko1234',
        'name' = > 'Tokyo',
    )
),
(int) 1 = > array(
    'Area' = > array(
        'id' = > 'osk1234',
        'name' = > 'Osaka',
    )
))

It is shown that
This may be a rudimentary question, but I would appreciate it if someone could tell me.
Thank you for your cooperation.

cakephp

2022-09-29 22:39

2 Answers

It uses a function called association.If it is the content of the question, set up an association of belongs to .

Refer to the documentation for the actual steps in CakePHP

http://book.cakephp.org/2.0/ja/models/associations-linking-models-together.html


2022-09-29 22:39

Create app/Model/Room.php where

<?php
   App::uses('AppModel', 'Model');

   class Room extensions AppModel {
      public$belongsTo=array('Area');
   }

create app/Model/Area.php and

<?php
   App::uses('AppModel', 'Model');

   class Area extensions AppModel {
      public$hasMany=array('Room');
   }

What do you think?


2022-09-29 22:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.