WmZilla - Webmaster and Marketplace

The Next Generation Webmaster and Trade Forum

Table Relationships in CakePHP

Moncho

New member

0

0%

Status

Offline

Posts

30

Likes

0

Rep

0

Bits

160

3

Months of Service

0%
In this opportunity, we will see how to relate tables with CakePHP, a fairly underestimated framework. If you are from the Symfony team, the structure of this framework will be interesting to you, but if you are from the Codeigniter team, some concepts may be unfamiliar.

We start by using the magical word "use" to be able to utilize certain classes and resources:

```php
use Cake\ORM\Table;
```

We have a class that extends from Table, and inside it, a method - since we are using OOP (Object-Oriented Programming), but you can call it a function if you prefer. Then, we have some setters. Remember I mentioned the Symfony team at the beginning? Further down, we have "belongsTo," which will be the way to relate tables. In this case, we have that a course can have a price:

```php
class CoursesTable extends Table
{

public function initialize(array $config): void
{
parent::initialize($config);

$this->setTable('courses');
$this->setDisplayField('name');
$this->setPrimaryKey('id');

$this->belongsTo('Prices', [
'foreignKey' => 'price_id',
'joinType' => 'INNER',
]);
}

}
```

Up to this point, everything's great, right? But do I have to do this manually? Well, the answer is no - with the command line tool "bake," the framework automatically generates the relationships for you.
 

249

6,622

6,642

Top