How to get and show data from different models in Cakephp - cakephp

I have 3 tables: orders, discounts and products in the way that product has many discounts (discount times). Discount has many orders. in other words, it looks like: Product > Discount > Order.
How can I get all data from 3 table, put it into one order view (do it in Order controller) and show it out (in Order view).
That's what I did, but It didnt work:
//Order controller
public function index() {
$this->Order->recursive=1;
$this->set('orders', $this->Order->find('all'));
}
// Order view
<?php foreach ($orders as $order): ?>
<tr>
<td><?php echo $order ['Order']['order_id']; ?></td>
<td><?php echo $this->Html->link($order['Product']['product_name'], array('controller' => 'products', 'action' => 'view', $order['Product']['product_id'])); ?></td> //I showed it here
<td><?php echo $order['Order']['order_date']; ?></td>
<td><?php echo $order['Order']['payment']; ?></td>
<?php endforeach; ?>
<?php unset($order); ?>
Please help me! thanks in advance.

Since you mention that you are in Order controller you can do any of these:
$this->Order->Behaviors->load('Containable');
$orders = $this->Order->find('all', array(
'contain' => array('Discount' => 'Product')));
$this->set(compact('orders'));
Now, in your view you can iterate over $orders variable.
PS: Of course, I am assuming here that Discount Belongs to Product.

You can do this easy way and different functionality
public function index() {
$this->set('datas',
$this->Order->find('all',
array (
'conditions' => array('Site_id' => $site_name),
'fields' => array('Date_time','Ac_1_Status','Tempin'),
'order' => array('id' => 'desc'),
'limit' => 200
)
)
);
}

Related

Cakephp application form

I created an application form using cakephp 2.
Now I want to know, How can users view only their application details using their user id. Here is the Form controller, the application form and the table for displaying the form
//Form controller
public function index() {
$this->set('posts', $this->Post->find('all'));
}
public function view($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
public function add() {
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Flash->success(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Flash->error(__('Unable to add your post.'));
}
}
//Create form
echo $this->Form->create('Post');
echo $this->Form->input('esta',['label'=>'New or Estabilished']);
echo $this->Form->end('Save Post');
//Form display
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Post']['id']; ?></td>
<td>
<?php echo $this->Html->link($post['Post']['describe_idea'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
<?php unset($post); ?>
</table>
You said that you are using cakephp 2.x please find below code to find record
for Single Record
$posts = $this->Post->find('first', array(
'conditions' => array('id' => 1)
));
For Multiple record
$posts = $this->Post->find('all', array(
'conditions' => array('id' => 1)
));
Add filter in your action
CakePHP 3.x
$posts = $this->Posts->find()
->where([
'Posts.user_id' => $this->Auth->user('id')
]);
CakePHP 2.x
$posts = $this->Posts->find('all', [
'user_id' => $this->Auth->user('id')
]);
Note: Make sure to login user to set Auth data.

how to add search by date cakePHP

I have the following code that displays a list of details from my Database.
It is paginated as well.
I want to add a search function that someone can search the provided data using " Date From - Date To "
Currenty source :
$tapplicant= $this->paginate = array(
'fields' => array(
'Tapplicant.*',
'Toutcome.*'
),
'joins' => array(
array(
'table' => 'toutcome',
'alias' => 'Toutcome',
'type' => 'INNER',
'conditions' => array('Tapplicant.AppID = Toutcome.AppID' )
)
),
'conditions' => array(
'Tapplicant.AppDate >=' => date('y-m-d')
),
'order' => array('Tapplicant.AppDate' => 'DESC'),
'limit' => 15
);
$this->set('tapplicant', $this->paginate());
I display the data as followed :
<?php foreach ($tapplicant as $tapplicant) : ?>
<tr>
<td><?=$tapplicant['Tapplicant']['AppID']; ?></td>
<td><?=$tapplicant['Tapplicant']['AppAffID']; ?></td>
<td><?=$tapplicant['Tapplicant']['FirstName']; ?></td>
<td><?=$tapplicant['Tapplicant']['LastName']; ?></td>
<td><?=$tapplicant['Tapplicant']['AppDate']; ?></td>
<td><?=$tapplicant['Tapplicant']['AppDomain']; ?></td>
<td>£<?=$tapplicant['Toutcome']['LenderCommission']; ?></td>
<td><?=$tapplicant['Toutcome']['LenderName']; ?></td>
</tr>
After doing some research and trying things like :
$this->Post->find('all', array('conditions'=>array('AppID'=>5, 'DATE(AppDate)'=>'CURDATE()')));
I cant get it to work.
If someone could please assist on help with the controller and view side.
Use BETWEEN:
$conditions = array(
'Tapplicant.AppDate BETWEEN ? AND ?' => array(
$start,
$end,
)
);
Read more about complex find conditions in CakePHP 2 here: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#complex-find-conditions

CakePHP Ajax search : Showing same data two times for pagination

Here ajax search working fine but the problem is same data is showing two times, because I have given pagination limit 2.If I make it 3, same result is showing 3 times.
Here is my index.ctp
$( "#search" ).keyup(function() {
var value=$('#search').val();
$.get("<?php echo Router::url(array('controller'=>'userTypes','action'=>'search'));?>",{search:value},function(data){
$('.search_data').html(data);
});
})
Here is my search action
public function search()
{
$search=$_GET['search'];
$request=$this->UserType->find('all', array(
'conditions' => array('UserType.name LIKE' => "%$search%")
));
$this->set('usertype',$request);
}
Here is the search.ctp
<?php foreach($usertype as $usertypes) { ?>
<tr>
<td><?php echo $usertypes['UserType']['id']; ?></td>
<td><?php echo $usertypes['UserType']['name']; ?></td>
<td><?php echo $usertypes['UserType']['description']; ?></td>
</tr>
<?php } ?>
Pagination limit In appcontroller
parent::beforeFilter();
$this->Paginator->settings = array(
'limit'=>2
);
Result is showing me like this
May anybody help me for solve it ?
If you want to use pagination, your search method should look like this:
public function search()
{
if(isset($this->request->query['search'])){
$search = $this->request->query['search'];
}else{
$search = '';
)
$this->Paginator->settings = array(
'conditions' => array('UserType.name LIKE' => "%$search%"),
'limit' => 2
);
));
$this->set('usertype',$this->Paginator->paginate());
}

CakePHP: ArraySource + Paginator

with CakePHP I want to use an array with the Paginator component. I'm using the Datasources plugin and I have created the Fake model:
<?php
/**
* A Fake model.
*/
class Fake extends AppModel {
public $useDbConfig = 'arraySource';
public $records = array(
array('id' => 1, 'name' => 'Alfa', 'height' => 300, 'width' => 300),
array('id' => 2, 'name' => 'Beta', 'height' => 200, 'width' => 100),
array('id' => 3, 'name' => 'Gamma', 'height' => 450, 'width' => 200),
array('id' => 4, 'name' => 'Omega', 'height' => 600, 'width' => 50)
);
}
On the controller:
<?php
class ExampleController extends AppController {
public $components = array('Paginator');
public $uses = array('Fake');
public function justatest() {
$this->Paginator->settings = array(
'order' => array('id' => 'desc'),
'limit' => 2
);
$records = $this->Paginator->paginate('Fake');
$this->set(compact('records'));
}
Now, the data is retrieved correctly by the component. The "limit" condition works correctly. What doesn't work is the "order" condition: it doesn't work or the condition that I have indicated, or sort the data according to user input.
I cannot understand if I've done something wrong or if I cannot sort the data obtained with ArraySource.
EDIT
The view:
<table>
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('name'); ?></th>
<th><?php echo $this->Paginator->sort('height'); ?></th>
<th><?php echo $this->Paginator->sort('width'); ?></th>
</tr>
<?php foreach($records as $v): ?>
<tr>
<td><?php echo $v['Fake']['id']; ?></td>
<td><?php echo $v['Fake']['name']; ?></td>
<td><?php echo $v['Fake']['height']; ?></td>
<td><?php echo $v['Fake']['width']; ?></td>
</tr>
<?php endforeach; ?>
</table>
Right from the top of my head, try this :
$this->Paginator->settings = array(
'order' => array('id DESC'),
'limit' => 2
);
Not sure at all

cakephp: how to render related models in the view

My objective is to display records for a related child model (once removed) in the view. My problem is that I receive a 'Notice (8): Undefined index:' error message when I try to output the following query.
Tournaments have many tournamentDetails, and tournamentDetails have many updates. I'm trying to display all the updates for each tournamentDetail that is displayed on the tournaments view.
So my question is how to properly resolve the error message and display the updates for each tournamentDetail on the tournaments view page.
My find data in the 'tournaments' controller view action is:
$updates = $this->Tournament->TournamentDetail->Update->find('all', array( 'tournament_details.tournament_id'=> $this->data['Tournament']['id']));
In the view, I have this code.
<?php foreach ($tournament['Update'] as $update): ?>
<h3>Updates</h3>
<h1><?php echo $update ['title']; ?></h1>
<p><?php echo $update ['body']; ?></p>
<hr/>
<?php endforeach; ?>
This is the same 'foreach' code the I use for the other related child records without problem. I did use the debug() function to investigate but didn't see what I was missing.
The output of the $updates array from the debug function looks like this:
Array
(
[0] => Array
(
[Update] => Array
(
[id] => 1
[title] => first round matches start today
[date] => 2010-03-19
[body] => this tournament's first round matches start today.
[tournament_detail_id] => 4
[homeStatus] => no
)
Is there a special way to display records this deep?
As always, thanks in advance.
Paul
Update: Feb 23/11
After some testing the problem I seem to have is finding and passing the correct value to the $updates variable;
To summarize, I want the $updates variable to hold the current 'tournament_details_id'. This will then display the related update records in the 'tournaments' view.
I'm still a beginner and most likely overlooked the obvious.
Here is the model info:
class Tournament extends AppModel {
var $name = 'Tournament';
var $hasMany = array(
'TournamentDetail' => array(
'className' => 'TournamentDetail',
'foreignKey' => 'tournament_id',)
class TournamentDetail extends AppModel {
var $name = 'TournamentDetail';
var $belongsTo = array(
'Tournament' => array(
'className' => 'Tournament',
'foreignKey' => 'tournament_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
class Update extends AppModel {
var $name = 'Update';
var $belongsTo = array(
'TournamentDetails' => array(
'className' => 'TournamentDetails',
'foreignKey' => 'tournament_detail_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Controller data:
class TournamentsController extends AppController
function view($slug = null) {
if (!$slug) {
$this->Session->setFlash(__('Invalid Tournament.', true));
$this->redirect(array('action'=>'index'));
}
$this->Tournament->recursive = 1;
$tournament = $this->Tournament->findBySlug($slug);
$updates = $this->Tournament->TournamentDetail->Update->find('all', array('conditions' => array( 'tournament_details_id' => $this->data['TournamentDetails']['id'] )));
$this->set(compact('tournament','updates', $updates ));
Tournament view. This is display the 'tournament details' and (ideally) related tournament detail 'updates'
<h2><?php echo $tournament['Tournament']['name']; ?></h2>
<?php foreach ($tournament['TournamentDetail'] as $tournamentDetail): ?>
<h1><?php echo $tournamentDetail ['title']; ?></h1>
<p><?php echo $tournamentDetail ['body']; ?></p>
<?php endforeach; ?>
<?php foreach ($updates['Update'] as $update): ?>
<h4>Update: <?php echo $update ['date']; ?></h4>
<p> <?php echo $update ['Update'] ['title']; ?></p>
<p><?php echo $update ['Update'] ['body']; ?></p>
<?php endforeach; ?>
I've tested this by adding in the tournament details 'id' as an integer and it pulls up the correct 'update' record. However I seem to have problems configuring the find operation to do the same.
As always I appreciate the help.
Thanks
Paul
Based on your debug output, it seems that your $tournaments variable consists of an array (instead of the associative array) so you might want to use the foreach to access each of those elements:
foreach ($tournaments as $update):
?>
<h3>Updates</h3>
<h1><?php echo $update ['Update']['title']; ?></h1>
<p><?php echo $update ['Update']['body']; ?></p>
<hr/>
<?php endforeach; ?>
It appears that you be using the wrong variable, you talk about the $updates variable but you're using the $tournament variable in your view.
<?php foreach ($updates['Update'] as $update): ?>
<h3>Updates</h3>
<h1><?php echo $update ['title']; ?></h1>
<p><?php echo $update ['body']; ?></p>
<hr/>
<?php endforeach; ?>
Additionally you haven't posted the whole controller method, which includes that find but you might not have sent the data to the view yet either
$this->set(compact('updates'));

Resources