How do I select only certain fields for associated data?

I’m trying to associate 2 models, but I’d like to only retrieve certain fields on the associated model. So, I have a menuitems model, and each menuitem is associated with a page:

class MenuitemsTable extends Table
{

    public function initialize(array $config)
    {
        $this->belongsTo('Pages');
    }
}

I retrieve the menuitems like this:

        $menuitems= TableRegistry::get('Menuitems');
        $query = $menuitems->find('all')
                                ->contain(['Pages']);

However, I only want to retrieve the page id and name when I get a menuitem, rather than the page content as well. I’m not sure how to go about this, and can’t find anything in the documentation that works.

I tried defining the association like this:

            $this->belongsTo('Pages', ['fields' => ['id', 'name']]);

but it dodn’t have any effect.

I’d be grateful for any help.

You would need something like this

$query = $menuitems->find('all')
    ->select(['Pages.id', 'Pages.name'])
    ->contain(['Pages']);
1 Like

Thanks. I’ll try that.