1
votes

I have three different tables.

  1. Users
  2. UserBids
  3. Company

Now I am retrieving data from User. Each User has many UserBids. Each UserBids BelongsTo Any Company.

Now I am writing a Query Like That.

$Users = $this->Users->find('all', array(
        'conditions' => array('Users.id' => $userid)
));

It is getting all the data regarding to User and UserBids.

But in UserBids Table, there is field and its name is company_id.

How can I get company name and other data by that company_id from Company Table?

3

3 Answers

2
votes

First of all, you should follow the CakePHP naming conventions. Model names should be singular.

Below is the code that you can use:

Your model files should looks like this:

app/Model/User.php

App::uses('AppModel', 'Model');
class User extends AppModel
{
    public $name = 'User';
    public $useTable = 'Users';    
    public $hasMany = array('UserBid' => array('className' => 'UserBids',
                                               'foreignKey' => 'user_id'));
}

app/Model/UserBid.php

App::uses('AppModel', 'Model');
class UserBid extends AppModel
{
    public $name = 'UserBid';
    public $useTable = 'UserBids';    
    public $belongsTo = array('Company' => array('className' => 'Company',
                                                 'foreignKey' => 'company_id'));
}

app/Model/Company.php

App::uses('AppModel', 'Model');
class Company extends AppModel
{
    public $name = 'Company';
    public $useTable = 'Company';
}

Now your find condition should looks like:

$user_details = $this->User->find('all', array('conditions' => array('Users.id' => $userid),
                                               'recursive' => 2));
2
votes

You are after the recursive option to find() - http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive. It takes an int which is the number of associations the find query will traverse through and return data for. The default value is 1 which explains your results.

0
votes

//this is for call UserBids table

$this->loadmodel('UserBids');

you can try like this

$fetch_data=$this->UserBids->find('all',array('conditions'=>array('UserBids.id'=>$_SESSION['UserAuth']['User']['id'])));

$this->set('selected', $fetch_data);