How should I link these models to query multi tables via CakePHP associations?

Stuhunohots

New Member
I am using cakephp 2.3.2 and I need to do a query on multi tables.I have this database:\[code\]--------------------------------------------------------------| Users | Agents | Companies | Ads |--------------------------------------------------------------| id | id | id | id || username | name | company | sector || password | lastname | vat | message || | user_id | user_id | user_id |--------------------------------------------------------------\[/code\]These are the associations (Models):User
  • hasOne Agent
  • hasOne Company
  • hasMany Ads
Agent
  • belongsTo User
Company
  • belongsTo User
Ad
  • belongsTo User
(NOTE: Please, keep in mind that when I add a new user that user could be an Agent OR a Company.)QUESTION:In my AdsController I have an action named view, there I read two params that I receve from Route:\[code\]$this->params['id']$this->params['sector']\[/code\]I need to do a query to check if the id is really associated to an Ad.id and If the sector is associated to Company.sectorI would like to check it with ONE find('first') instead of checking[*]If the ID exists[*]If the sector exists and it is associated to the user_idHow could I do it ?(If the query finds Ad.id and Company.sector I need to retrieve all fields of Ad and Company)At the moment my find('first') in AdsController/view is:\[code\]$options = array( 'fields' => array( 'Ad.*' ), 'contain' => array( 'User' => array( 'Company' => array( 'fields' => array( 'Company.*' ), 'conditions' => array( 'Company.sector' => $this->params['sector'], ), ) ) ), 'conditions' => array( 'Ad.id' => $this->params['id'], ))$data = http://stackoverflow.com/questions/15895156/$this->find('first', $options);debug($data);\[/code\]The problem is that Company is now shown in the result (array).Please, keep in mind that I only need to retrieve the array IF:
  • The ID of the AD exists
  • The sector of the Company exists
If one of above are not "true" I would like to get an empty array.Obviously I have added Containable behavior in Ad model.
 
Top