Friday, March 28, 2008

Tags, Tags cloud, behaviors etc...b

I am based my compilation of this useful stuff on This Article.

But, DW aka "dooltaz" made some mistakes in his code.

First of all you need to created model
post.php:

VALID_NOT_EMPTY,
'email' => VALID_EMAIL,
'body' => VALID_NOT_EMPTY,
);

var $actsAs = array('Tag'=>array('table_label'=>'tags', 'tags_label'=>'tag', 'separator'=>','));


var $hasAndBelongsToMany = array('Tag' =>
array('className' => 'Tag',
'joinTable' => 'posts_tags',
'foreignKey' => 'post_id',
'associationForeignKey'=> 'tag_id',
'conditions' => '',
'order' => '',
'limit' => '',
'unique' => true,
'finderQuery' => '',
'deleteQuery' => '',
)
);

}
?>


nest make posts_tag.php



And the last tag.php

array('className' => 'Post',
'joinTable' => 'posts_tags',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'post_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);

}
?>

don't forget to create table in your MySQL database ;-)

Model Post: posts must have fields:

id (bigint)
tags (text) - it's field need to HABTM working properly ;-))

Model Tag: tags

id (bigint)
tag (text, or varchar 255)

Join model posts_tags:

post_id (bigint)
tag_id (bigint)

Ok? Ok!

Now, if you use CakePHP 1.2.0.6311-beta, you'll need to make some things with /lib/model.php

Look at track - ticket.

Ok? Ok! In next post I told you how to make view cloud ;-)

Labels: , , ,

Wednesday, March 12, 2008

CakePHP 1.2: paginator and custom query

Hello everybody!

;-)

Today I'm broken my brain for making custom query in paginator ;-)

So. Let's begining!

I have two models (don't ask why ;-)

Post: id, body, ...
Answer: id, post_id, body ...

What I need? I want to search for %query% in Answer.body and in Post.body.

But!

I want to get list only like this: site.com/posts/view/id

Other words: if I found %query% in both body (Answer.body and Post.body) I don't need to get 2 url. Only one.

How to get it with SQL (MySQL)? It's so easy if you use DISTINCT in your query.

But, after 2 hours with cofee and brainstorming... I made this code:

$datas = $this->Post->findAll($query,"id");
foreach ($datas as $key => $value) {
$dat .= $value['Post']['id'] . " ";
}
$dat = explode (" ",$dat);
$dat = array_unique ($dat);
array_pop($dat);
$dat = implode(",",$dat);
$this->Post->recursive = -2;
$this->paginate = array ('limit' => '10','conditions' => 'Post.id IN ('. $dat .')', 'order' => 'Post.created DESC');

Yes, it's not so good idea, but it's simple, it's work. And I think - Keep It Simple St... ;-)

If you have better idea, I very glad to see your code!

Labels: , , , ,