开发者

CakePHP database how it works? [closed]

开发者 https://www.devze.com 2023-02-25 00:07 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the 开发者_如何学Chelp center. Closed 11 years ago.

I have 3 tables: users, images (foreign key to user_id), comments (foreign keys: user_id and image_id)

Can somebody explain me or send me link to good tutorial how to work with database? I mean e.g.: 1. I wants to take all Images which have any comment in Comments table. In SQL: select i from Images i, Commets c where i.id=c.image_id???

Can You explain me how can I access from one controller to another Model? I was trying in Images controller: $data = $this->Image->query('Select * from Images i, Comments c where i.id=c.image_id'); And in view: $image['id'] but I have error:Undefined index: id [APP\views\images\commented.ctp,

SO it does not work:/

  1. How can I delete Image and all its comments? I used Zend and I get used to it and I have no idea how to do the same thinks in cakePHP :/

Can somebody explain me how to work with database in this cakePHP I know there are find, findAll etc functions but all of them are from a controller level ex. $this->Image->find() etc...

I need better tutorial than the basic cakePHP cookbook :/. I am open for any sugestions. Regards,


You reference models in the controller in one of many ways. The two common ways are with the uses variable at the top of the controller:

var $uses = array('User','Image');

Or you can put it inline in your functions:

$this->loadModel('Image');
$this->Image->find('all'); ...

In addition, if you have the models linked by a foriegn key, you can even call it like:

$this->User->Image->find('all');

Once you get the hang of how CakePHP structures things, it makes it very clear.

So for your sql statement in the question, you could do something like the following from the users controller:

class UsersController extends AppController {
   var $name = 'Users';
   var $uses = array('User','Image','Comments');

   function {my_function_name}() {
       $this->Images->recursive = 1;
       $images = $this->Image->find('all');
   }
}

Now, as long as your relationships are correct in the model, the recursive function will build the images array with all of the comments attached to it.

array(
   [Image] => array(
        image data,
        [comments] => array(
            [0] comment data,
            [1] comment data,
            [2] ...
        )
    )
)

I hope that at least pushes you in the right direction. Happy coding!

0

精彩评论

暂无评论...
验证码 换一张
取 消