@deron
To make a join in CakePHP, you can use the association methods provided by the CakePHP ORM. Here's an example of how to perform a join:
1 2 3 4 5 6 7 8 9 10 11 |
namespace AppModelTable;
use CakeORMTable;
class UsersTable extends Table
{
public function initialize(array $config): void
{
$this->hasMany('Posts');
}
}
|
In the Post.php table class:
1 2 3 4 5 6 7 8 9 10 11 |
namespace AppModelTable;
use CakeORMTable;
class PostsTable extends Table
{
public function initialize(array $config): void
{
$this->belongsTo('Users');
}
}
|
1 2 |
use AppModelTableUsersTable; use AppModelTablePostsTable; |
1 2 3 4 |
$postsTable = new PostsTable();
$posts = $postsTable->find('all')
->contain('Users')
->toArray();
|
The contain() method will perform a join on the associated table and retrieve the related data.
1 2 3 4 5 |
$posts = $postsTable->find('all')
->contain('Users', function($q) {
return $q->select(['username']);
})
->toArray();
|
This will optimize the retrieved data by only fetching the required fields.