简体   繁体   中英

CakePHP get data from a table that class belongs_to

I have a model in cakePHP:

class PagesTable extends Table
{
  public function initialize(array $config)
{
    $this->addBehavior('Timestamp');

    $this->belongsTo('Pagecats');

    $this->belongsToMany('Users');
}

and another model PagecatsTable:

class PagecatsTable extends Table
{
public function initialize(array $config)
{
    $this->addBehavior('Timestamp');
}

which its table has two coloumns id and category

How can I get the category in a function in my PagesController?

In your PagesController, do you want the pages and their associated records? If so, you could try the below mentioned code:

// PagesController.php

$data = $this->Pages->find()
  ->contain('Pagecats')
  ->all();

pr($data->toArray()); // Check if you're getting the desired result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM