Skip to content

Instantly share code, notes, and snippets.

Created April 17, 2014 13:48
Show Gist options
  • Save anonymous/10984799 to your computer and use it in GitHub Desktop.
Save anonymous/10984799 to your computer and use it in GitHub Desktop.
swt's contain
<?php
// File: app/Model/Client.php
App::uses('AppModel','Model'); // Let cake know you need the AppModel file
class Client extends AppModel
{
// Relation with Job Model -------------
public $hasMany = array('Job');
}
<?php
// File: /app/Controller/ClientsController.php
App::uses('AppController','Controller');
class ClientsController extends AppController
{
// Load the Html and Form Helper:
public $helpers = array('Html', 'Form');
// Load the SesionComponent so we can use setFlash():
public $components = array('Session');
# ----------------------------------------- #
# - INDEX action -------------------------- #
# ----------------------------------------- #
public function index()
{
// Get all the Clients and pass them to index.ctp as $clients:
$this->set('clients', $this->Client->findAll());
}
# ----------------------------------------- #
# - VIEW Client action -------------------- #
# ----------------------------------------- #
// This gets called when people go to ../clients/view/
public function view($id = null)
{
// If there is no Client ID passed:
if(is_null($id)):
/* Display a message on next page load
(your layouts file should fetch this
somewhere - default.ctp will already do it) */
$this->Session->setFlash('Hey, you need to pick a Client to view!');
// Redirect the user to the index page to pick a Client:
$this->redirect('index');
endif;
// Tell your Client model to also contain the Job data:
$this->Client->contain(array('Job'));
// Get the data from the database and store it as $client:
$client = $this->Client->findById($id);
// Pass Client to the view.ctp file:
$this->set('client', $client);
} // end View
}
<?php
// File: app/Model/Job.php
App::uses('AppModel','Model'); // Let cake know you need the AppModel file
class Job extends AppModel
{
// Relation with Client Model --------------
public $belongsTo = array('Client');
}
<!-- File: /app/View/Clients/view.ctp -->
<?php
echo "Client Name: ".$client['name'];
echo "Client has the following jobs <br />";
foreach($client['Job'] as $job):
echo $job['name'];
endforeach;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment