Trying to make a filter to retrieve data from related models - cakephp

I have a Post model which hasMany PostField
every post can have several fields stored in the post_fields table..
post_fields has this structure: (id, post_id, name, value)
posts table has some common fields for all posts, but any additional fields should be stored in post_fields table..
I created a search form that is used to filter the posts
when specifying filters for the fields in the posts table, it works fine..
but I want to make the filter to work even on the other fields found in post_fields ..
I can retrieve the posts first then filter them manually, but i want something more efficient !
EXAMPLE: let's suppose that posts are describing some products..
post (id, title, created, price)
post_fields (id, post_id, name, value)
in this case, all posts have title, created and price..
but if a post (id=3) wants to have a weight field, we should do that by creating a record in post_fields, the record should be :
{ id: .. , post_id: 3, name: weight, value: .. }
it's easy now to filter posts according to price (e.g. price between min & max)..
but, what if i want to filter posts according to weight ??
e.g. i want all posts that have weight greater than 10 !!
I would like to achieve this preferably in one query, using joins maybe or subqueries ..
I don't know how to do that in cakePHP, so if any one has an idea, plz HELP !!
even if someone just has an idea but doesn't have details, that could help ...
thanx in advance !

There is no way to search against the children of a hasMany relationship. You will need to run your query against the PostFields model. ie: $this->PostField->find('all', array('conditions'=>array('PostField.name' => 'weight', 'PostField.value' > 10)));
If you want to do a query against both the PostField and Post models at the same time (ie: price < $1.00 and weight > 10, you will need to do a custom query, as CakePHP has no built-in solution for doing so TMK. Should look something like this:
$query = "SELECT ... FROM posts as Post, post_fields as PostField WHERE PostField.name = 'weight' AND PostField.value > 10 AND POST.price < 1.0 AND PostField.post_id = Post.id;"
$posts = $this->Post->query($query);
EDIT:
I would do this. You're not going to get away with doing a single call, but this is still a clean solution.
$postIds = null;
if(/*we need to run query against PostFields*/) {
$conditions = array(
'OR' => array(
array(
'AND' => array(
'PostField.name' => 'weight',
'PostField.value' > 10
)
),
array(
'AND' => array(
'PostField.name' => 'height',
'PostField.value' < 10
)
)
)
);
$fields = array('PostField.id', 'PostField.post_id');
$postIds = $this->Post->PostField->find('list', array('conditions'=>$conditions, 'fields'=>$fields));
}
$conditions = array('Post.price' < 1.0);
if($postIds) {
$conditions['Post.id'] = $postIds;
}
$posts = $this->Post->find('all', array('conditions'=>$conditions));

You should look into using the Containable behavior for your models. This way, you can filter the returned columns as you like. (I think this is the type of filtering you want to do)

Related

Pagination of query ignoring the LIMIT clause in CakePHP 3.x

I am trying to create a query that would only return 2 results, and by following the documentation I get the query to run, however the limit is still set to 20 by default.
Here is how the query is built:
$upcomingMeetings = $this->Meetings->find('all')
->where(['Meetings.user_id' => $this->Auth->User('user_id')])
->andWhere(["Meetings.date >= " => date('Y-m-d') ])
->order(['Meetings.date' => 'ASC'])
->limit(2);
The result is being passed to the view like following:
$this->set('upcomingMeetings', $this->paginate($upcomingMeetings));
Here is the query that is being run on the database:
SELECT
Meetings.id AS `Meetings__id`,
Meetings.date AS `Meetings__date`,
Meetings.user_id AS `Meetings__user_id`,
FROM
meetings Meetings
WHERE
(
Meetings.group_id = 7
AND Meetings.date >= '2016-01-14'
)
ORDER BY
Meetings.date ASC
LIMIT
20 OFFSET 0
Any help or guidance is much appreciated.
When paginating a Query object, CakePHP will ignore the limit() clause and use the value defined in the $paginate configuration array instead.
This is what can be concluded after inspecting the source code.
Try adding the following to your controller:
public $paginate = [
'limit' => 2,
];

CakePHP: Save data in two models

In CakePHP I have two models: Clients & Tickets. A client can have many tickets and a ticket can only have 1 client.
When adding a new ticket I want to automatically create a new client by only entering a name. So the form would be:
Name = "Name client" >> Name should be save in Client table en new client_ID in Ticket table
Info = Ticket information >> Save in Ticket table.
"Save"
I'm not sure how this works. I have associations in the model and tried to saveAll but there is no data stored in the Client table. And how do I get the ID in the Ticket table?
Hope someone can point me in the right direction. I've searched for other answers but cant seem to find a solution. Is saveAll the right way to do this?
You should set a php condition before insert values into the table, the sql request 4 exemple return the numbers of repetition of the same ticket_id so if the returned value is greater than 1 the request can't execute else the request insert the values
The function to count number of rows : mysql_num_rows('request');
You can use the callback methods.
If you have defined your relation in the Ticket model with belongsTo Client, it will be accessible from that model.
public $belongsTo = array(
'Client' => array(
'className' => 'Client',
'foreignKey' => 'client_id',
),
);
So, if you want to make a new client before saving the ticket, you can do:
public function beforeSave ($options = array()) {
$this->data['Client']['name'] = $someVar;
$this->Client->save($this->data);
$this->data[$this->alias]['client_id'] = $this->Client->getInsertID();
return true;
}

Select from 2 tables in Symfony2

I am making a query inside a form.
The idea is : Now I have a dropdown with all the users, ok?
I have a query like this:
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')->orderBy('u.lastName', 'ASC');
}
This works flawless!
Instead of displaying all the users, I only need the users that are associated with a category. This definition is in the "user_data" table (user_id + category_id).
So, I need to do something like:
SELECT * FROM users
WHERE user_id IN (SELECT user_id FROM user_data WHERE category_id='2')
I don't have any entity that looks like UserData, I only have User.php, but inside this file I found this:
/**
*#ORM\ManyToMany(targetEntity="My\Bundle\Entity\Data", inversedBy="users")
*#ORM\joinTable(name="user_data")
*/
protected $datas;
[...]
So I see that a relationship is build, but I don't get it how to use it in order to build my query based on the 2 tables...
Anyone can help me with this issue? :)
Thanks!
Try this,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->innerJoin('u.datas', 'd')
->where('d.category = :category') // Check your Data entity to get the right field name
->setParameter('category', $yourCategoryId) // you could use options here
->orderBy('u.lastName', 'ASC');
}
Also, update your question with all your entities (Data, ...)

CakePHP - Retrieving and working with data from different tables

I'm sorry, I am a newbie in CakePHP and I am a little bit confused in this subject, let me explain:
I have a relationship between two tables. One of the table is Dose and the other is tank. So, one Tank belongs to a Dose. A Dose has many Tanks. The table schema is:
CREATE TABLE `doses` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`dose` INT(5) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
In my Tank view I have the following code:
<?php echo $form->input('dose_id', array('class'=>'input', 'label' => ''));?>
Each 'dose' (field) from Dose table correspond to a value, such as 200, 300, and so forth. I need to use these numbers to calculate others numbers before to insert into my database (table tank). For instance, my code in tanks_controllers:
$t_u = $this->data['Tank']['tipo_uso_id'];
if( $t_u == '1'){
$this->data['Tank']['producao_adubo_diaria'] = $this->data['Tank']['dose_id'] * 0.10;
.
.
.
However, it is bringing to me the ID of the Dose and not the value (dose field). Where can I set up this to bring me the correct data (dose)? I tried to set up this way in my model:
'Dose' => array(
'className' => 'Dose',
'foreignKey' => 'dose_id',
'conditions' => '',
'fields' => 'dose',
'order' => ''
)
It did not work.
I appreciate your time helping me.
Thanks in advance.
it is bringing to me the ID of the Dose and not the value (dose field). Where can I set up this to bring me the correct data (dose)?
You need to get it from the db (model), not from the view. So you need to do a find(). If you are new to Cake, you should read the cookbook first to see how it works.
What does $form->input('dose_id') produce? A dropdown? If so; by default cake will produce a dropdown with the value containing (dose_)id, and the text you see as the value of $displayField(usually name/title).
To do this; if I understand you, you would need to first query doses for all the values and store the result in an array using the dose value as the key AND the value, rather than the id as you normally would. You would then be able to access the actual dose value from $this->data.
$doseArray=array();
$doses = $this->Dose->find('all');
foreach($doses['Dose'] as $k => $v) {
$doseArray[$v] = $v;
}
perhaps. Seems a bit redundant so I might be off.

whats wrong with this query

I have this in my table model called Table
$test = $this->find('first', array(
'conditions' => array('table.test_id is NULL'),
'order'=> array('table.created ASC'),
)
);
it doesnt work. Tryingt to get the latest row with some criteria
Well, first of all, to get the latest row, you would want to organize by the created field descending, rather than ascending. Also, there are some problems with your syntax, that I have cleaned up below.
$this->find('first', array('conditions'=>array('Table.test_id'=>NULL), 'order'=>array('Table.created'=>'desc')));

Resources