Retrieve posts with their latest comment in CakePHP - cakephp

Say I have a model Post and a model Comment related as follows:
Post hasMany Comment
Comment belongsTo Post
How do use find('all') to retrieve every Post with its associated latest Comment?
I have tried defining a hasOne relationship in Post as:
var $hasOne = array('LatestComment' => array('className' => 'Comment', 'order' => 'LatestComment.created DESC'));
But when I do a Post->find('all') it returns every Post multiple times, once per each Comment, with LatestComment set to the different Comments.

You can add 'limit' => 1 to your array of parameters to only return one comment.
Alternatively, instead of defining another relationship, you can simply limit the number of comments returned when you perform the find, using the Containable behaviour.
$this->Post->find('all',array(
'contain' => array(
'Comment' => array(
'order' => 'Comment.created DESC',
'limit' => 1
)
)
);
This is useful if you want to filter any related sets without defining relationships - by author, or within a date range, for example.
Make sure that you add the Containable behaviour to any model that you reference.

To remove the duplicates you want to use: GROUP BY in your find all query. I believe Cake has a 'group' => option as well.

Related

Ways to use array in cakephp

Hello I am having a tought time figuring out how to use arrays in cakephp. right now i have a view with 2 columns, active and startYear. i need to grab the start years for all of the columns in the view and sho i have this code.
public function initialize(array $config)
{
$this->setTable('odb.SchoolYear');
}
controller
public function index()
{
$deleteTable = $this->loadModel('DeletedTranscripts');
$this->$deleteTable->find('all', array(
'conditions' => array(
'field' => 500,
'status' => 'Confirmed'
),
'order' => 'ASC'
));
$this->set('startYear',$deleteTable );
}
once i have the array captured and put into lets say startYear can in input a statement like this into my dropdown list to populate it?
<div class="dropdown-menu">
<a class="dropdown-item" href="#"><?= $delete->startYear; ?></a>
</div>
i have been looking for answers for quite awhile any help would be awesome.
Couple of things:
Loading Tables in CakePHP
For this line:
$deleteTable = $this->loadModel('DeletedTranscripts');
While you can get a table this way, there's really no reason to set the return of loadModel to a variable. This function sets a property of the same name on the Controller, which almost correctly used on the next line. Just use:
$this->loadModel('DeletedTranscripts');
Then you can start referencing this Table with:
$this->DeletedTranscripts
Additionally, if you're in say the DeletedTranscriptsController - the corresponding Table is loaded for you automatically, this call might be unnecessary entirely.
Getting Query Results
Next, you're close on the query part, you've can start to build a new Query with:
$this->DeletedTranscripts->find('all', array(
'conditions' => array(
'field' => 500,
'status' => 'Confirmed'
),
'order' => 'ASC'
));
But note that the find() function does not immediately return results - it's just building a query. You can continue to modify this query with additional functions (like ->where() or ->contain()).
To get results from a query you need to call something like toArray() to get all results or first() to get a single one, like so:
$deletedTranscriptsList = $this->DeletedTranscripts->find('all', array(
'conditions' => array(
'field' => 500,
'status' => 'Confirmed'
),
'order' => 'ASC'
))->toArray();
Sending data to the view
Now that you've got the list, set that so it's available in your view as an array:
$this->set('startYear', $deletedTranscriptsList );
See also:
Using Finders to Load Data
Setting View Variables
I also noticed you've had a few other related questions recently - CakePHP's docs are really good overall, it does cover these systems pretty well. I'd encourage you to read up as much as possible on Controller's & View's.
I'd also maybe suggest running through the CMS Tutorial if you've not done so already, the section covering Controllers might help explain a number of CakePHP concepts related here & has some great working examples.
Hope this helps!

CakePHP conditions clause on associations when using Model::find()

I just confused because of a find() result. This is my configurations:
First, users can have different User.role values: student, admin, and some others.
// Book
public $belongsTo = array(
'Student' => array(
'className' => 'User',
'foreignKey' => 'student_id'
'conditions' => array('User.role' => 'student')
);
);
When I chain Models like $this->Book->Student->find('list'); I was expecting to get only users whose role are 'student', but instead, it gets all users. What is going on here, what is conditions for on association definition, where can it and cannot be used. Any lead would help, thanks.
PS: I am aware that I could put conditions on find(), that's not the issue
There is a difference between associated data and accessing an associated model object. If you access $this->Book->Student you're accessing the Student model and work in it's scope. The conditions in the defined associations work only in the context of the accessed object.
So if you do a find on the Book and list the students for that book:
$this->Book->find('first', array('contain' => array('Student'));
Your code will work correctly. It will find the book plus the first user who has the role stundent. BUT your association is wrong then: It should be hasMany. because why would you filter a book by role if the book just belongsTo one student?
If you want to filter users by their role you can implement a query param that is checked in beforeFind(), pseudocode: if isset roleFilter then add contention to filter by that role from roleFilter.
Or, if you don't need to paginate just create a getStudents() method in the user model that will return a find('list') that has the conditions.
Or Student extends User and put the filter in the beforeFind() and use that model instead of the User model in your Book association.
If you want to filter on model level or per model I think the last one is a good option. Don't forget to set $useTable and $name or the inherited model will cause problems.
you have miss , inside your model.
try this:
public $belongsTo = array(
'Student' => array(
'className' => 'User',
'foreignKey' => 'student_id', //<------ miss
'conditions' => array('User.role' => 'student')
);
);
Yoi can debug your query to check what is the real query that you make.
Personally I have never use this approach, I prefer to use foreign key with another table for examples Rolesand User.role_id.
Is better for me to use this approach to have more flexibility inside your app.
After I prefer to use a conditions where inside controller to check well the query, because in your way every query you search always for student role not for the other and can be a problem for the rest of role, because inside controller you see a find without conditions but it doesn't take right value because in your model there is a particular conditions.
For me the good way is to create a new table, use foreign key and where conditions inside action of the controller to view well what are you doing.
For default all relations are "left join", you must set the parameter "type" with "inner" value
// Book
public $belongsTo = array(
'Student' => array(
'className' => 'User',
'foreignKey' => 'student_id'
'conditions' => array('Student.role' => 'student'), // <-- Fix That (field name)
'type' => 'inner', // <-- add that
);
);

CakePHP 2.4.4 How can I structure this find() with Containable?

Tables
User(id)
Profile(id, *user_id*, type)
Attribute(id, *attribute_name_id*, value)
AttributeName(id, name)
ProfileAttribute(id, *profile_id*, *attribute_id*)
Relationships
The relationships are set up correctly (and go both ways, hasMany/belongsTo).
User hasMany Profile
Profile hasMany ProfileAttribute
Attribute hasMany ProfileAttribute
(could be written Profile hasMany Attribute through ProfileAttribute)
AttributeName hasMany Attribute
Goal
For a specified User id, with a find() in the User model, I only want the following fields, laid out as such:
$results[Profile.type][AttributeName.name][Attribute.value]
Is it even possible to retrieve results arranged like this? I've been playing around with Find and Containable for hours, but, first time trying to do anything complicated like this with Cake, I can't get the hang of it.
Thanks!
EDIT
I'm getting these results now, all that I need, but nowhere near the desired format above -can it be done as part of the find, or does it need to be sorted after?
Yep, it's possible. You just have to specify fields on containable:
$this->User->find('all', array(
'conditions' => array('User.id' => $id),
'fields' => array('id'),
'contain' => array(
'Profile' => array(
'fields' => array('id','type'),
'ProfileAttribute' => array(
'fields' => array('id'),
'AttributeName' => array(
'fields' => array('id','name'),
'Attribute' => array(
'fields' => array('id','value')
)
)
)
)
)
);
Be wary that when you use contain and fields options, you have to specify the id so it can make the association (check the docs)
EDIT: I don't know if you can group contained data as the docs didn't say anything about that, but probably you can, as they accept some parameters as in the main query. You can try it, adding group to any contained data that you want to group

how to use cakedc/search plugin for searching across 3 different tables with 1 search bar?

I am using CakePHP2.4 and the search plugin https://github.com/CakeDC/search
I have the following
Employee hasOne EmployeeProfile
Employee hasMany Qualification
So I have a single search bar.
the search bar will search using LIKE through the following fields
Employee.name
EmployeeProfile.email
Qualification.title
how do I configure the model Employee->filterArgs for this search?
This is a cross-posting of the original issue here
The documentation includes an example.
'username' => array('type' => 'like', 'field' => array('User.username', 'UserInfo.first_name')),
You just have to make sure the models you're calling are available in your find() call. In the example the find will do a like on the users table username and on the user_infos first_name field at the same time.
I'd like to expand on this as I've been trying to setup a search on a hasMany relationship for a few hours and couldn't find anything. Mark mentionned "custom bindModel (as hasOne) for hasMany relationship (Qualification)". Here's how it's done :
$this->Employee->bindModel(array(
'hasOne' => array(
'Qualification' => array(
'foreignKey' => false,
'conditions' => array('Employee.id = Qualification.employee_id')
)
)
), false);
Just bind it before your paginate and add Qualification.title in your field list in your filterArgs

cakephp: find statement with 'contain'

the following User model function is from MilesJones forum plugin. Can someone tell me on what is the use of 'contain' in the find stmt. I couldn't find any example with contain in the cakephp cookbook. Any helps is appreciated.
public function getProfile($id) {
return $this->find('first', array(
'conditions' => array('User.id' => $id),
'contain' => array(
'Access' => array('AccessLevel'),
'Moderator' => array('ForumCategory')
)
));
}
By default when a find statement executes cake pulls all the data from the model on which the find function is executing plus all the data from the models that are associated with the model. Most of the time you don't need that extra data, Cake has containable behaviour for exactly that purpose. You can specify which associated model's data you want in your result.
In the above example find statement will fetch the first record from the User model plus associated data from Access and Moderator models.
Here is the link from cakephp book http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
Here is cakephp documentation about contain

Resources