fetching data from multiple tables in Cakephp - php

I am new in cakephp and trying my best to implement queries in cakephp.
I have this query
SELECT * FROM question join question_topic on question.question_id=question_topic.question_id join topic on topic.topic_id=question_topic.topic_id join user_topic on user_topic.topic_id=topic.topic_id where user_topic .user_id=10
I need this in cakephp.
What I have tried is this
$this->Behaviors->attach('Containable');
return $this->find('all', array(
'contain' => array(
'User',
'UserInfo.UserTopic'=>array(
'conditions'=>array('UserTopic.user_id'=>10)
),
'QuestionAndTopic.Topic','UpVoteQuestion','Answer','Answer.UserInfo'
),
'order' => 'rand()',
'recursive' => 0
));
But the query is not giving me a right results. Could you please take a look.
Question.php
class Question extends AppModel
{
public $useTable = 'question';
public $primaryKey = 'question_id';
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'fields' => array('User.user_id','User.email','User.active')
),
'UserInfo' => array(
'className' => 'UserInfo',
'foreignKey' => 'user_id',
)
);
public $hasMany = array(
'Answer' => array(
'className' => 'Answer',
'foreignKey' => 'question_id',
),
'QuestionAndTopic' => array(
'className' => 'QuestionAndTopic',
'foreignKey' => 'question_id',
)
);
public function latestQuestions(){
$this->Behaviors->attach('Containable');
return $this->find('all', array(
'contain' => array(
'User',
'UserInfo.UserTopic'=>array(
'conditions'=>array('UserTopic.user_id'=>10)
),
'QuestionAndTopic.Topic','UpVoteQuestion','Answer','Answer.UserInfo'
),
'order' => 'rand()',
'recursive' => 0
));
}
}

You can use Mysql query it will works as like as cakephp query
$this->Behaviors->query('SELECT * FROM question join question_topic on question.question_id=question_topic.question_id join topic on topic.topic_id=question_topic.topic_id join user_topic on user_topic.topic_id=topic.topic_id where user_topic .user_id=10');

Refer this link
$options['joins'] = array(
array('table' => 'books_tags',
'alias' => 'BooksTag',
'type' => 'inner',
'conditions' => array(
'Book.id = BooksTag.book_id'
)
),
array('table' => 'tags',
'alias' => 'Tag',
'type' => 'inner',
'conditions' => array(
'BooksTag.tag_id = Tag.id'
)
)
);
$options['conditions'] = array(
'Tag.tag' => 'Novel'
);
$books = $Book->find('all', $options);
make changes as per you table and fields.hope this helps.

Related

Join query in cakephp

Hello I am new in Cakephp and I am having a hard time converting mysql queries in cakephp.I have this query which I want to convert into Cakephp syntax
SELECT *
FROM trip
JOIN countries ON trip.departure_country_id = countries.id
WHERE countries.country_name LIKE "eng%"
This is what I have tried so far
class Trip extends AppModel
{
public $useTable = 'trip';
public $primaryKey = 'trip_id';
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'fields' => array('User.user_id','User.first_name','User.last_name','User.profile_image','User.country','User.phone_no')
),
'departure_country' => array(
'className' => 'Country',
'foreignKey' => 'departure_country_id',
),
'arrival_country' => array(
'className' => 'Country',
'foreignKey' => 'arrival_country_id',
)
);
public function getLocationBasedTrips($country){
return $this->find('all', array(
'conditions' => array(
'OR' => array('Country.country_name Like' => '%'.$country.'%')
),
));
}
}
Trip Model:
$this->find('all',
array(
'joins' => array(
array(
'table' => 'countries',
'alias' => 'Country',
'type' => 'INNER',
'conditions' => array(
'Trip.departure_country_id = Country.id'
)
),
'conditions' => array(
'Country.country_name Like' => "%$country%"
)
)
);
Moved some brackets around from the previous answer. Try this:
$this->find('all', array(
'joins' => array(
array(
'table' => 'countries',
'alias' => 'Country',
'conditions' => array(
'Trip.departure_country_id = Country.id'
)
)
),
'conditions' => array(
'Country.country_name LIKE' => "%$country%"
)
)
);

CakePHP JOIN not working

I am new in cakephp and I have searched a lot but couldn't get the solution. My query is not returning any error but it doesn't join the zone table with the disposeTemp table.
public function disposePreview(){
$this->loadModel('DisposeTemp');
$joins = array(
array(
'table' => 'zones',
'alias' => 'Zone',
'type' => 'inner',
'conditions' => array('DisposeTemp.zone = Zone.id')
)
);
$options = array(
'conditions' => array('DisposeTemp.is_delete' => 0,'DisposeTemp.status'=>2),
'order' => array('Item.item_category_id' => 'asc'),
'joins' => $joins
);
$getDT = $this->DisposeTemp->find('all', $options);
debug($getDT);
exit;
}
Set foreign key false , as you are not having proper naming convention for foreign key in DisposeTemp table , it was supposed to be zone_id to auto form relationship.
Now in your situation Use.
$joins = array(
array(
'table' => 'zones',
'alias' => 'Zone',
'type' => 'inner',
'foreignKey' => FALSE,
'conditions' => array('DisposeTemp.zone = Zone.id')
)
);

HABTM Cake php find

I have tables below with HABTM associations.
user, group , groups_users
group , project, projects_groups
public $hasAndBelongsToMany = array(
'Group' =>
array(
'className' => 'Group',
'joinTable' => 'groups_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'group_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => ''
)
);
I am trying to get all users, as a list for checkboxes, that are on a project using project id using query below
$users = $this->User->Group->Project->find('list',
array(
'conditions' => array('Project.id' => $this->Session->read('Projectid'))
,'contain' => array(
'User' => array( 'fields' => 'User.id', 'User.email')
)
)
);
But error below
Model "Project" is not associated with model "User"
I have actually tried different ways to get this working but cant seem to get it right, how can i achieve what i want. cheers
I achieved what i wanted with joins , is there a way to do this by using model associations, instead of the manual joins option?
$options['joins'] = array(
array('table' => 'groups_users',
'alias' => 'gu',
'type' => 'LEFT',
'conditions' => array(
'gu.user_id = User.id',
)
),
array('table' => 'projectGroups',
'alias' => 'pg',
'type' => 'LEFT',
'conditions' => array(
'pg.group_id = gu.group_id',
)
)
);
$this->User->recursive = -1;
$options['conditions'] = array(
'pg.project_id = ' => $this->Session->read('Projectid'),
'User.Active = ' => true
);
$users = $this->User->find('list', $options);

Cakephp cannot pull associated Model details via Belongsto

I have below defined in my model:
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'GroupBuy' => array(
'className' => 'GroupBuy',
'foreignKey' => 'group_buy_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
This however does not pull details from GroupBuy nor User table but it fetches only user_id and group_buy_id which are defined in this GroupBuyUser model.
I've set recursive two with below:
$this->GroupBuyUser->recursive = 2;
Is there something wrong I'm doing here?
Try the following code in your GroupBuyUser Model:
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
),
'GroupBuy' => array(
'className' => 'GroupBuy',
'foreignKey' => 'group_buy_id'
)
);
You don't need to set the recursive property to 2. This is basically used while we want to fetch result from deeper associated models.

Confusion with HABTM IN Cakephp

I have 3 tables structure as...
SONG(id, status)
TRACKLIST(id, song_id, artist_id, status)
ARTIST(id, status)
I wish to have HABTM so I mentioned as..
Song MODEL
var $hasAndBelongsToMany = array(
'Artist' => array(
'className' => 'Artist',
'joinTable' => 'tracklists',
'foreignKey' => 'song_id',
'associationForeignKey' => 'artist_id',
'conditions' => array('tracklist.status' => '1')
'with' => 'Tracklist',
//'unique' => true
),
);
Artist Model
var $hasAndBelongsToMany = array(
'Song' => array(
'className' => 'Song',
'joinTable' => 'tracklists',
'foreignKey' => 'artist_id',
'associationForeignKey' => 'song_id',
'with' => 'Tracklist',
//'unique' => true
),
);
Tracklist Model
var $belongsTo = array(
'Song' => array(
'className' => 'Song',
'foreignKey' => 'song_id',
'dependent' => true
),
'Artist' => array(
'className' => 'Artist',
'foreignKey' => 'artist_id',
'dependent' => true
)
);
This way but issue is when I tried to find records from the Artist table it find all the records without any condition.
$artist_conditions = array('Artist.status' => '1');
$artist_list = $this->Song->Artist->find('list', array('conditions' => $artist_conditions ));
I wish to fetch only those artist related to the tracklist and having tracklist.status as 1. Is the relationship is correct?? Or I simply use hasMany with (Song, Artist) and BelongsTo with (Tracklist).
You can try this:
/* for example in songs controller */
public $uses = array('Song','Tracklist');
$artist_conditions = array('Artist.status' => '1');
$this->Tracklist->recursive = 1;
$artist_list = $this->Tracklist->find('list', array('conditions' => $artist_conditions ));

Categories