Sultanen
Sultanen

Reputation: 3412

How to perform a join in CakePHP?

How do you perform a joins in CakePHP like for example the one below for MySQL?

SELECT *
FROM yarns y
JOIN yarn_brands yb
JOIN contents ct
WHERE y.id = ct.yarn_id
AND yb.id = y.yarn_brand_id
AND ct.material_id = 2

I have tried to search around for the answer but i dont find anything that works. I found something about "contain", i have tried this but i get the result that the query it produces doesent include a join of the table requested to join in.

$this->Message->find('all', array(
    'contain' => array('User')
    'conditions' => array(
        'Message.to' => 4
    ),
    'order' => 'Message.datetime DESC'
));

Upvotes: 0

Views: 734

Answers (2)

Sultanen
Sultanen

Reputation: 3412

This is the join i ended up with:

            $options['contain'] = '';
            $options['joins'][0]['table'] = 'contents';
            $options['joins'][0]['alias'] = 'cont';
            $options['joins'][0]['conditions'] = 'Yarn.id = cont.yarn_id';
            $options['joins'][1]['table'] = 'yarn_brands';
            $options['joins'][1]['alias'] = 'yb';
            $options['joins'][1]['conditions'] = 'yb.id = Yarn.yarn_brand_id';
            $options['fields'] = array('Yarn.name');
            $options['conditions']['cont.material_id'] = $this->request->data['Yarn']['material_id'];
            $options['conditions']['Yarn.yarn_brand_id'] = $this->request->data['Yarn']['yarn_brand_id'];

Upvotes: 0

BadHorsie
BadHorsie

Reputation: 14544

CakePHP makes all this very simple, provided you have read the book about model relationships and have set up your models and datebase tables accordingly. This is a really essential part of CakePHP, and what will make up a lot of your application. If you understand how to do this the 'Cake' way, it will make your life much easier.

http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html#model-and-database-conventions

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

For your MySQL example, try this code. Obviously I don't know exactly what your model relationships are, but here is a guess based on the MySQL.

// app/Model/Yarn.php
class Yarn extends AppModel {

    public $belongsTo = array('YarnBrand');

    // You might need this as $hasOne instead, I can't tell from the MySQL alone.
    public $hasMany = array('Content');

}

// app/Model/YarnBrand.php
class YarnBrand extends AppModel {

    public $hasMany = array('Yarn');

}

// app/Model/Content.php
class Content extends AppModel {

    public $belongsTo = array('Yarn');

}

Code to find all Yarns, along with their YarnBrand and Contents

$this->Yarns->find('all', array(
    'conditions' => array(
        Content.material_id' => 2
    ),
    'contain' => array(
        'YarnBrand',
        'Content'
    )
));

Upvotes: 1

Related Questions