CakePHP - Retrieving and working with data from different tables - cakephp

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.

Related

Insert new row in wordpress table but delete all others

I'm trying to add a new row in a wordpress table (that i've created), but every times that i add the new row, all the others are deleted and if i look DB table i can see only last inserted row.
I've tried two methods, but i get the same results:
$ins_reply = $wpdb->insert( $table, array('itemid'=> $item_id, 'time' => $time, 'title' => '', 'text' => $content, 'author' => $user, 'deadline' => 0));
OR
$query_insert = "INSERT INTO ".$table." (`itemid` ,`time` ,`title` ,`text` ,`deadline` ,`author`) VALUES ('".$item_id."', '".$time."', '', '".$content."', '0', '".$user."')";
$wpdb->query($query_insert);
What's wrong in my code?
Your query as posted in your question is not the source of your issue.
Perhaps you are working on a plugin where the table creation script is accidentally wiping & re-installing the table during this operation?

Cakephp insert sql statement

I'd like to insert data into a mysql table using 'the cakephp way'.
I have a multi-stage program that stores data to a session, and toward the end of the program I'd like to write the session data to the database. I could do this using a standard sql insert statement but would like to know how this should be done using cakephp. (Most of the cakephp doc discusses sending data from a webform, and I'd like to manually submit session data.)
Should I manually format the session data in this format and then send this to the model? And if so, is there a helper function for this?
Array
(
[ModelName] => Array
(
[fieldname1] => 'value'
[fieldname2] => 'value'
)
)
Yes, that's the way to do it. There's really no need for a helper function, just use the ones you normally would.
$name = 'Foo';
$city = 'Bar';
$this->ModelName->save(
array(
'name' => $name,
'city' => $city
)
);

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')));

Trying to make a filter to retrieve data from related models

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)

CakePHP - HABTM - adding multiple tags to multiple points

I am trying to 'tag' multiple 'points' with multiple tags. I'm tagging my single points successfully. Unfortunately, when i try and use a tag, such as 'test2' on another point as a tag it is either giving me a duplicate entry error if i have my 'unique' set to false or if 'unique' is set to true, it will del my tag for all other points for 'test2' and create a single new one.
Here is what i have for my post data:
Array
(
[Tag] => Array
(
[id] => 4b7af6d7-787c-4f10-aa49-2502c0a80001
[name] => Test2
)
[Point] => Array
(
[id] => 4b47c66f-a130-4d12-8ccd-60824051e4b0
)
)
In my tag model i have this:
public $hasAndBelongsToMany = array(
'Point' => array(
'className' => 'Point',
'joinTable' => 'points_tags',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'point_id',
'unique' => false)
);
I have tried this with 'unique' set as true, too. Unfortunately, this will delete any other instances of 'Test2' in the join table ('points_tags').
I have tried this using both save() and saveAll(). Both are giving me this error:
Warning (512): SQL Error: 1062: Duplicate entry '4b7af6d7-787c-4f10-aa49-2502c0a80001-4b47c66f-a130-4d12-8ccd-608' for key 'MAN_ADD' [CORE/cake/libs/model/datasources/dbo_source.php, line 527]
Query: INSERT INTO points_tags (tag_id,point_id,id) VALUES ('4b7af6d7-787c-4f10-aa49-2502c0a80001','4b47c66f-a130-4d12-8ccd-60824051e4b0','4b7b39f3-46f8-4744-ac53-3973c0a80001')
Thoughts????
Suggestions????
Where does the id come from? I'm guessing its a primary key of the table, and from what I understand from your post (please write more clearly, help us help you) the problem isn't with points or tags, but with the id in the points_tags table.
When you use the save method, are you doing it inside of a loop? Remember, best practice is to call model::create() whenever you're saving in a loop.
I frequently find that when I have issues with the HABTM saving behavior, it's because I didn't call model::create.

Resources