简体   繁体   中英

CakePHP: How do I load associated data from inside an entity class?

Let's say I have a AuthorsTable with a defined "belongs to many" association with the Articles table defined like so:

// In the initialize function of the AuthorsTable class.
$this->belongsToMany('Articles',
    ['joinTable' => 'authors_articles']
);

(I don't think that the nature of the join is relevant to the question, but just in the interest of giving full context.)

And now, a I have an $author entity that was passed to my function that does not have the associated data loaded with it (ie, it was created using something like $author = $authorsTable->get(19); , so it only has the information in the authors table, not from the articles table.

Is there some kind of entity function in which I can load the associated data, ie, the articles data after the entity has already been created?

It's a little bit over and I do not know if it's still important to you, but maybe for everyone else. You can either use the model's loadInto ( https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#loading-additional-associations ) or you can just use the Lazy Loading Plugin, mentioned in the docs ( https://book.cakephp.org/3.0/en/orm/entities.html#lazy-loading-associations )

You can find the plugin here: https://github.com/jeremyharris/cakephp-lazyload

The plugin works with both methods! If you prefer Eager Loading , you can use contain (normaly faster). Otherwise, the associations will be loaded "on demand" (saving memory).

Personally, I prefer Eager Loading but use the Lazy Loading Plugin if another member of the team (out of ignorance) forgot to load the Associations.

chriss's answer suggests using loadInto for this. For CakePHP 3, the PHP you need within any Author Entity method is:

TableRegistry::get($this->source())->loadInto($this, ['Articles']);

The same code from within an AuthorsTable method:

$this->loadInto($author, ['Articles']);

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