I have a table name countries , countries has relation with users, users has relation with MoneyTransferTransactions
In MoneyTransferTransactions view I need fetch country name.
I already join Users table in MoneyTransferTransactionsTable by below code
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
In user table I also used inner join like below code
$this->belongsTo('Countries', [
'foreignKey' => 'country_id',
'joinType' => 'INNER'
]);
In MoneyTransferTransactions controller I have used below code to fetch all data with associated data.
$this->paginate = [
'contain' => ['Users','TransferOptions'],
'conditions'=> ['MoneyTransferTransactions.status'=>1],
'order' =>['MoneyTransferTransactions.id'=>'DESC']
];
I have used var_dump in index.ctp , I gotted country id from users table but not got country name from countries table. How can I get country name from MoneyTransferTransactions>index.ctp ?
Add association between Users and Countries in 'contain'
$this->paginate = [
'contain' => ['TransferOptions', 'Users' => ['Countries']],
'conditions' => ['MoneyTransferTransactions.status' => 1],
'order' => ['MoneyTransferTransactions.id' => 'DESC']
];
Related
We have 4 tables
Users
-id
Profiles
-id
-user_id
Questions
-id
Options
-id
ProfileQuestions
-id
-profile_id
-question_id
-option_id
Now i require to get all profiles and each profile have multiple questions and each question has many options.
User Model
$this->hasMany('Profiles', [
'foreignKey' => 'user_id'
]);
Profiles Model
$this->belongsToMany('Questions', [
'foreignKey' => 'profile_id',
'targetForeignKey' => 'question_id',
'joinTable' => 'profile_questions',
'through' => 'ProfileQuestions' ,
'joinType' => 'LEFT']);
Questions Model
$this->belongsToMany('Options', [
'foreignKey' => ['question_id'],
'targetForeignKey' => 'option_id',
'joinTable' => 'profile_questions',
'through' => 'ProfileQuestions'
]);
ProfileQuestions Model
$this->belongsTo('Profile', [
'foreignKey' => 'profile_id',
]);
$this->belongsTo('Questions', [
'foreignKey' => 'question_id'
]);
$this->belongsTo('Options', [
'foreignKey' => 'option_id'
]);
Controller code to get the result
$query = $this->Users->find('first')
$query->contain(['Profiles.Questions.Options']);
Error
Fatal error: Out of memory (allocated 408944640) (tried to allocate 665912212 bytes) in vendor\cakephp\cakephp\src\Database\Statement\MysqlStatement.php on line 39
Issue is related to Associations. If we set the profile_id where condition with the options contain then it works for that profile id.
I dont understand from the docs why I cant retrieve selected fields from associated data.
I have 2 many to many relationships in the contain which displays everything fine.
$query3 = $this->find()
->contain(['Subjects','AvailabilityForStudents'])
->select([
'Students.id','Students.first_name','Students.last_name','Students.address_billing','Students.address_lat','Students.address_long',
'Students.class_year','Students.address_street','Students.address_suburb','Students.address_postcode','Students.address_state'])
->where(['Students.id IN' => $stids])
->order(['Students.first_name' => 'ASC'])
->hydrate(true);
My Question is that instead of getting every field from the contained models why cant I select fields from the contained model as below? I am not selecting based on a criteria like in matching clause?
$query3 = $this->find()
->contain(['Subjects','AvailabilityForStudents'])
->select(['Subjects.name','Subjects.id','AvailabilityForStudents.id',
'Students.id','Students.first_name','Students.last_name','Students.address_billing','Students.address_lat','Students.address_long',
'Students.class_year','Students.address_street','Students.address_suburb','Students.address_postcode','Students.address_state'])
->where(['Students.id IN' => $stids])
->order(['Students.first_name' => 'ASC'])
->hydrate(true);
//student model
$this->hasMany('AvailabilityForStudents', [
'className' => 'AvailabilityForStudents',
'foreignKey' => 'student_id',
'dependent' => false,
]);
$this->belongsToMany('Subjects', [
'foreignKey' => 'student_id',
'targetForeignKey' => 'subject_id',
'joinTable' => 'subjects_students'
]);
//update contain
$query3 = $this->find()
->contain([
'Subjects'=>['fields'=>['name','id','SubjectsStudents.student_id']],
'AvailabilityForStudents' ])
// ->contain(['Subjects','AvailabilityForStudents'])
->where(['Students.student_unallocated' => 1,'Students.student_inactive' => 0])
->order(['Students.first_name' => 'ASC'])
->hydrate(true);
https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html
You are doing right.
You can try this also,
$query3 = $this->find()
->contain([
'Subjects'=>['fields'=>['name','id','SubjectsStudents.student_id']],
'AvailabilityForStudents'=>['fields'=>'id']
])
->select(['Students.id','Students.first_name','Students.last_name','Students.address_billing','Students.address_lat','Students.address_long',
'Students.class_year','Students.address_street','Students.address_suburb','Students.address_postcode','Students.address_state'])
->where(['Students.id IN' => $stids])
->order(['Students.first_name' => 'ASC'])
->hydrate(false)->toArray();
Cakephp pagination with join table sort is not working for join table fields. But for custom sql join query working fine. Please help me to come out.
See below sample code.. I have Artist.name join table field in order.
$this->paginate = array(
'fields' => array(
'id',
'Song.title',
'Song.date',
'Artist.id AS artist_id',
'Artist.name AS artist_name',
'COUNT(SongViews.id) AS views'
),
'group' => array('ArtistsSong.song_id'),
'recursive' => 0,
'limit' => 20,
'joins' => array(
array(
'table' => 'tbl_artists_songs',
'alias' => 'ArtistsSong',
'conditions'=> array('Song.id = ArtistsSong.song_id')
),array(
'table' => 'tbl_artists',
'alias' => 'Artist',
'conditions'=> array('Artist.id = ArtistsSong.artist_id')
),array(
'table' => 'tbl_song_views',
'alias' => 'SongViews',
'type' => 'left',
'conditions'=> array('SongViews.song_id = ArtistsSong.song_id')
),
),
'order' => array('Artist.name'=>'asc')
);
It is a bug in CakePHP.
However, there is a trick to do it.
You should add a virtual field in your primary model.
Assuming your primary model is Song, you should add this before calling paginate:
$this->Song->virtualFields = array(
'artist_name' => 'Artist.name'
);
And now, you can sort by artist_name.
This question was asked nearly 5 years ago, but I came across the same problem in CakePHP 3. I realised I needed to whitelist the field to allow for sorting:
$this->paginate = array(
...
'sortWhitelist' => array ('Artist.name')
);
The Paginator automatically whitelists fields from the original table but not from the JOINed tables.
$this->paginate = ['fields' => ['id', 'name', 'company_id'],
'contain' => [
'Companies' =>
[
'fields' => ['id', 'name'],
'sort'=>['name'=>'ASC']
]
'limit' => 10,
];
Sorting by columns in associated models requires setting sortWhitelist.
$this->paginate['order'] = [ 'Artist.name' => 'desc' ];
$this->paginate['sortWhitelist'] = ['Artist.name', 'Song.title'];
$this->paginate['limit'] = $this->paginate['maxLimit'] = 200;
In HTML you have to set below line in table header:
<?= $this->Paginator->sort('Song.title', __('Title')) ?>
i have a two tables namely; histories and users. i need to display data like:
id | Username | Lastest created Post | First created Post
the data of id and username is from users table and the last created and first created post data is from histories. i need to view all the users, their lastest created post and their first created post. please help me to make controller and view thanks
Try below.
<?php
$users = $this->User->find('all',array
(
'conditions' => array
(
//conditions goes here
),
'fields' => array
(
'User.id',
'User.username',
'History.Lastest created Post',
'History.First created Post'
)
));
?>
Assume that relation between 'User' and 'History' table is One-to-One and there's a 'user_id' column in History table, you may need to specify relation between them in History model, for example:
var $hasOne = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Then, you need to perform joins to do this. For example, somewhere in your User model, try something like this:
class User extends AppModel {
....
function getAllUsersHistory{
$allHistories = $this->find('all', array(
'joins' => array(
'table' => 'history',
'alias' => 'HistoryJoin'
'type' => 'INNER',
'conditions' => array(
// your conditions, for example: 'History.user_id' => 'User.id'
)
),
'fields' => array(
'User.id',
'User.username',
'History.lastest_created_post',
'History.first_created_post'
)
));
return $allHistories;
}
.....
}
Im new to cakePHP and the whole table relations concept is very confusing!
I have 2 tables, competencies and competenceRatings. competencies stores a list of names with ids.
competencies
------------
id
name
And users can select various competencies from this table and rate them and their ratings are stored into competenceRatings table.
competenceRatings
-----------------
id
competence_id
user_id
rating
I want to be able to get the names of competencies for which a user have NOT made any ratings into competenceRatings table. i.e., I need list of names from competencies table for which there are no entries in comptenceRatings table(for given user_id).
I tried competencies->hasMany->competenceRatings, competenceRatings->belongsTo->competencies relations.
$competencies = $this->Competence->CompetenceRating->find('all',array('CompetenceRating.user_id' => $userId,'CompetenceRating.competence_id !=' => 'Competence.id'));
But no use!
Does this result require any other relations? Or can i just join tables using joins condition in find query?
Thanks.
EDIT
This method worked:
$options['joins'] = array(
array(
'table' => 'competence_ratings',
'alias' => 'CompetenceRating',
'type' => 'LEFT OUTER',
'conditions' => array(
'Competence.id = CompetenceRating.competence_id',
'CompetenceRating.user_id' => $userId
)
)
);
$options['conditions'] = array( 'CompetenceRating.competence_id'=> null );
Try this
Joining tables
$data = $this->Competence->find('all', array('joins' => array(
array(
'table' => 'competenceRatings',
'alias' => 'CompetenceRating',
'type' => 'inner',
'foreignKey' => false,
'conditions'=> array('CompetenceRating.competencie_id = Competence.id')
),
array(
'table' => 'competencies',
'alias' => 'Competence',
'type' => 'inner',
'foreignKey' => false,
'conditions'=> array(
'Competence.id = MarkersTag.tag_id',
'Competence.user_id' => $user_id
)
)
)));