I have an Articles model and Ratings model. An Article hasMany Ratings. I want to find the 10 highest rated Articles in the past 60 days.. The problem as I see it is that i have to get the sumOf 'score' on a containable model.
This is what I have tried:
$articles = $this->Articles->find()
->where( 'Articles.publish >' => (new Time())->subDays(60))
->contain([
'Ratings' => function ($q) {
return $q->select(['id', 'article_id', 'total' => func()->sum('score')
]);
},
])
->order(['Ratings.total' => 'DESC']);
The other approach would be to query Ratings first to tge the 10 highest total scores then leftJoin on Articles. This doesn't seem very efficient though as I have 2500+ articles and I don't want to add overhead by totalling score for Articles that won't be included as they are to old to be included.
Please check below code using left join
$query = $this->Articles->find();
$query->limit( 10 );
$query->where( ['Articles.created >' => (new Time())->subDays(60)]);
$query->select( [
'Articles.id',
'Articles.title',
'sumrating' => $query->func()->sum( 'Ratings.rating' ),
'Articles.created',
'Articles.modified'
] );
$query->leftJoin(
[ 'Ratings' => 'ratings' ],
[ 'Ratings.article_id = Articles.id' ]
);
$query->group( [ 'Articles.id' ] );
$query->order( [ 'sumrating'=> 'DESC' ] );
$articles = $query ;
$this->set(compact('articles'));
Related
Products belongsToMany Categories and Categories hasMany Products, inside my Product view I'm showing a list of all it's categories but I want to paginate or limit these results.
My current code on ProductsController is:
$product = $this->Products
->findBySlug($slug_prod)
->contain(['Metas', 'Attachments', 'Categories'])
->first();
$this->set(compact('product'));
I know I need to set $this->paginate() to paginate something but I can't get it working to paginate the categories inside the product. I hope you guys can understand me.
UPDATE: Currently I have this going on:
$product = $this->Products->findBySlug($slug_prod)->contain([
'Metas',
'Attachments',
'Categories' => [
'sort' => ['Categories.title' => 'ASC'],
'queryBuilder' => function ($q) {
return $q->order(['Categories.title' => 'ASC'])->limit(6);
}
]
])->first();
The limit works but I don't know how to paginate yet
The paginator doesn't support paginating associations, you'll have to read the associated records manually in a separate query, and paginate that one, something along the lines of this:
$product = $this->Products
->findBySlug($slug_prod)
->contain(['Metas', 'Attachments'])
->first();
$categoriesQuery = $this->Products->Categories
->find()
->innerJoinWith('Products', function (\Cake\ORM\Query $query) use ($product) {
return $query->where([
'Products.id' => $product->id,
]);
})
->group('Categories.id');
$paginationOptions = [
'limit' => 6,
'order' => [
'Categories.title' => 'ASC'
]
];
$categories = $this->paginate($categoriesQuery, $paginationOptions);
$this->set(compact('product', 'categories'));
Then in your view template you can display your $product and separately paginate $categories as usual.
See also
Cookbook > Controllers > Components > Pagination
Cookbook > Views > Helper> Paginator
Cookbook > Database Access & ORM > Query Builder > Filtering by Associated Data
I'm having some trouble with Cakephp Query builder and try to get results I'm looking for. I have three tables 'Users', 'Items', 'Owns', where Owns belongs to both 'Users' and 'Items'.... A user can own many items (and many of the same items).
So I'm wanting to return the "owned" items by a user along with the count... However whenever I add count into my query I lose the associated Items data.
example - this returns the user data along with associated owns data and associated items data as shown below the query
$owns = $this->Users->get($id, [
'contain' => [
'Owns' => function($q) { return $q->find('all')->group(['Owns.item_id']); },
'Owns.Items'
],
]);
SQL Generated from this is
SELECT
Owns.id AS Owns__id,
Owns.item_id AS Owns__item_id,
Owns.user_id AS Owns__user_id,
Items.id AS Items__id,
Items.name AS Items__name,
Items.description AS Items__description,
Items.created AS Items__created,
Items.modified AS Items__modified
FROM
owns Owns
INNER JOIN items Items ON Items.id = (Owns.item_id)
WHERE
Owns.user_id in (1)
GROUP BY
Owns.item_id
Data results look like this:
'owns' => [
'id' => (int) 1,
'username' => 'myusername',
'owns' => [
(int) 0 => object(App\Model\Entity\Own) id:0 {
'id' => (int) 2
'item_id' => (int) 1
'user_id' => (int) 1
'item' => object(App\Model\Entity\Item) id:1 {
'id' => (int) 1
'name' => 'Item Name'
'description' => 'Item Description'
However in the 'owns' query I want to add in the count (i.e. the number owned). I can get the count by using this query but then I lose the associated item object from my results. I've tried this many different ways but always seems that if I want to use SQL count I can't get the associated data.
$owns2 = $this->Users->get($id, [
'contain' => [
'Owns' => function($q) { return $q->select(['count' => $q->func()->count('Owns.id'),'Owns.id', 'Owns.user_id', 'Owns.item_id'])->group(['Owns.item_id']); },
'Owns.Items'
],
]);
SQL Generated from this is
SELECT
(COUNT(Owns.id)) AS count,
Owns.id AS Owns__id,
Owns.user_id AS Owns__user_id,
Owns.item_id AS Owns__item_id
FROM
owns Owns
INNER JOIN items Items ON Items.id = (Owns.item_id)
WHERE
Owns.user_id in (1)
GROUP BY
Owns.item_id
Data results look like this:
'owns2' => [
'id' => (int) 1,
'username' => 'myusername',
'owns' => [
(int) 0 => object(App\Model\Entity\Own) id:36 {
'count' => (int) 4
'id' => (int) 2
'user_id' => (int) 1
'item_id' => (int) 1
Any insight into how I can get "count" into the first $user query or the associated items into the $user2 would be appreciated.
To keep the association table's fields that are returned in the $owns = find('all') query along with the SQL count function I needed to add the associated fields into the select statement
$owns2 = $this->Users->get($id, [
'contain' => [
'Owns' => function($q) { return $q->select(['count' => $q->func()->count('Owns.id'),'Owns.id', 'Owns.item_id','Owns.user_id', 'Items.id', 'Items.collection_id','Items.name', 'Items.description'])->group(['Owns.item_id']); },
'Owns.Items'
],
]);
Right now I've got two tables "Category" and "Product".
I made 'category_id' in "Product" to be equal 'id' in Category, so now in my view it shows all products of that category. But now I need one product to be in several categories.
In controller I use the following data provider:
$dataProvider = new ActiveDataProvider([
'query' => $query = Product::find()->where(['category_id' => $cats->id]),
'sort'=>array(
'defaultOrder'=>['id' => SORT_ASC],
),
'pagination' => [
'pageSize' => 9,
],
]);
Any suggestions on how to realise this feature?
if I did not understand it wrong your data structure to the pricipio
from 1 to N
Categories -> Products
and now you want it to be from N to N
a category with many products and a product with many categories.
So I would like you to create another table called Product_Categy where you keep the primary keys of the 2 tables there and you have to be able to make relations from N to N, you would have a final scheme like this
Categories (id, ...) ->
Categria_Product (id, id_categoria, id_producto, ...) <- Product (id, ..)
Try this:
$dataProvider = new ActiveDataProvider([
'query' => $query = Product::find()->where(['id' => $product_id]),
'sort'=>array(
'defaultOrder'=>['id' => SORT_ASC],
),
'pagination' => [
'pageSize' => 9,
],
]);
OR
$dataProvider = new ActiveDataProvider([
'query' => $query = Product::find()->where(['id' => $product_id])->groupBy(['cats->id']),
'sort'=>array(
'defaultOrder'=>['id' => SORT_ASC],
),
'pagination' => [
'pageSize' => 9,
],
]);
Order HasOne Suborder
Suborder BelongsTo Order
I need to sort Orders by a field in Suborders, but sorting by virtual fields appears to have been removed in Cake 3.x
In OrdersTable.php, I have
$this->hasOne('Suborder', [
'className' => 'Suborders',
'foreignKey' => 'order_id',
'strategy' => 'select',
'conditions' => function ($exp, $query) {
return $exp->add(['Suborder.id' => $query
->connection()
->newQuery()
->select(['SSO.id'])
->from(['SSO' => 'suborders'])
->where([
'Suborder.order_id = SSO.order_id',
'SSO.suborder_type_id in' => [1, 2, 3]
])
->order(['SSO.id' => 'DESC'])
->limit(1)]);
}
]);
In OrdersController.php, I have
$this->paginate = [
'limit' => 20,
'order' => ['id' => 'desc'],
'sortWhitelist' => [
'id',
'title',
'client_order',
'substatus',
'Workflows.order_status_id',
'Clients.name',
'ProductTypes.type',
'Suborder.due_date',
'Suborder.created',
],
];
$orders = $this->paginate($collection);
In index.ctp, I have
$this->Paginator->sort('Suborder.created', 'Order Placed'),
$this->Paginator->sort('Suborder.due_date'),
and the error I'm getting is Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Suborder.created' in 'order clause'. How do I get Cake to include the Suborder in the initial query for sorting and pagination?
Edit:
$collection = $this->Orders->find()
->contain([
'Clients',
'CurrentAssignment.Users',
'Workflows.OrderStatuses.Category',
'Workflows.OrderStatuses.Departments' => function ($q) use ($uID) {
return $this->Departments->find()->matching('Users', function ($q) use ($uID) {
return $q->where(['Users.id' => $uID]);
});
},
'ClientProducts.ProductTypes',
'Reviews' => function ($q) {
return $q->where(['review_type_id is not' => 6]);
},
'Reviews.ReviewTypes',
'PublicNotes',
'ActiveReview',
'Suborder',
'Suborder.SuborderTypes',
'Suborders.SuborderTypes',
]);
and $collection is modified with 150 lines of wheres, orWheres, and joins based on a number of conditions.
You have configured the assocaition to use the select strategy, which will use a separate query to retrieve the data (currently wrongly documented), hence you cannot reference it in the main query used for pagination.
So you have to use the default join strategy instead if you want to sort on it.
See also
Cookbook > Database Access & ORM > Associations - Linking Tables Together > HasOne Associations
Here I have a events field which have a realtion with passwords.I need to order all passwords by download_count DESC. So I have tried below code. It's not giving me any error but desc is not working.
$event = $this->Events->get($id, [
'contain' => [
'EventPasswordAll.Passwords' => [
'queryBuilder' => function (Query $q) {
return $q->order(['download_count' => 'DESC']);
}
]
]
]);
I have also tried
return $q->order(['Passwords.download_count' => 'DESC']);
I get the query
SELECT EventPasswordAll.id AS `EventPasswordAll__id`, EventPasswordAll.event_id AS `EventPasswordAll__event_id`, EventPasswordAll.password_id AS `EventPasswordAll__password_id`, Passwords.id AS `Passwords__id`, Passwords.name AS `Passwords__name`, Passwords.collection_id AS `Passwords__collection_id`, Passwords.photo_count AS `Passwords__photo_count`, Passwords.download_count AS `Passwords__download_count`, Passwords.created AS `Passwords__created`, Passwords.expires_at AS `Passwords__expires_at`, Passwords.recommended AS `Passwords__recommended`, Passwords.accepted AS `Passwords__accepted`, Passwords.user_id AS `Passwords__user_id` FROM event_password_all EventPasswordAll INNER JOIN passwords Passwords ON Passwords.id = (EventPasswordAll.password_id) WHERE EventPasswordAll.event_id in (14)
How to add order in queryBuilder for associative data ?
With an association of EventPasswordAll belongsTo Passwords, the passwords table record will be retrieved via a join, as can be seen in the query. In this case there is no query for Passwords, and thus the query builder is not being invoked.
You have to set the order for the EventPasswordAll query builder instead, like
$event = $this->Events->get($id, [
'contain' => [
'EventPasswordAll' => [
'queryBuilder' => function (Query $q) {
return $q->order(['Passwords.download_count' => 'DESC']);
},
'Passwords'
]
]
]);