php - How should I link these models to query multi tables via CakePHP associations? -
i using cakephp 2.3.2 , need query on multi tables.
i have database:
-------------------------------------------------------------- | users | agents | companies | ads | -------------------------------------------------------------- | id | id | id | id | | username | name | company | title | | password | lastname | sector | message | | | user_id | user_id | user_id | --------------------------------------------------------------
these associations (models):
user
- hasone agent
- hasone company
- hasmany ads
agent
- belongsto user
company
- belongsto user
ad
- belongsto user
(note: please, keep in mind when add new user user agent or company.)
question:
in adscontroller have action named view, there read 2 params receve route:
$this->params['id'] $this->params['sector']
i need query check if id associated ad.id , if sector associated company.sector
i check one find('first') instead of checking
- if id exists
- if sector exists , associated user_id
how ?
(if query finds ad.id , company.sector need retrieve fields of ad , company)
at moment find('first') in adscontroller/view is:
$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 = $this->ad->find('first', $options); debug($data);
the problem company shown in result (array).
please, keep in mind need retrieve array if:
- the id of ad exists
- the sector of company exists
if 1 of above not "true" empty array.
obviously have added containable behavior in ad model.
i've seen this, had same problem reason contain, kinda malfunctions array() structure, maybe works how means be, dont it, anyways retrive chain dependencies use kind of construction:
$options = array( 'contain' => array( 'user', 'user.company' => array( 'conditions' => array( 'company.sector' => $this->params['sector'], ), ) ), 'conditions' => array( 'ad.id' => $this->params['id'], ) )
but, need have in mind conditions in contain not same conditions main model, therfore if company sector not exist ad given id exits not receive empty set. far know cannot use condition exclude results if there no direct association between models. still need check if $result['user']['company']
empty set or not.
one more thing query array not match structure you've provided question, there no field sector
in company
table
Comments
Post a Comment