简体   繁体   中英

CakePHP HABTM find … not returning expected results

I'm hoping somebody can clear up this issue I am having. None of the other answers on SO seemed to help me out for some reason.

I have 2 tables with a HABTM relationship. Publications have many authors, and authors have many publications. In my case, I am attempting to output a list of all of the publications in the database, along with their corresponding authors.

I have the following tables:

publications:

id title

0 TestPublication

authors:

id firstname lastname middle

0 John Doe A

authors_publications:

id author_id publication_id

0 0 0

The 'id' column of each table is set as the primary key.

My Publication model looks like:

class Publication extends AppModel {

    var $name = 'Publication';
    var $hasAndBelongsToMany = array(
        'Author'=>array(
            'className'=>'Author'
        )
    );     
}

And finally, the PublicationsController has the following function:

function index() {
$publications = $this->Publication->find('all');
$this->set('publications', $publications);
}

Here is what publications now contains:

Array ( [0] => Array ( [Publication] => Array ( [id] => 0 [title] => TestPublica [type_id] => 1 ) [Author] => Array ( ) ) ) 

Why is this? I am expecting (perhaps that is my problem...) that the author John Doe should be present in the Author array. If it should be, where am I going wrong? Do I need a bindModel call somewhere in there?

Or...is the code actually executing the way it should and my expectations are incorrect? If so, how would I return a list of all of the publications along with all of their authors?

Thanks for your time!

I believe I found the problem. I was manually inserting records into the DB for testing purposes. I set the primary key id's on the first record of each table to zero. SQL DBs typically (or always?) start the first record with a primary key index of 1, not 0. I'm not sure WHY cake did not work with this, but changing the id's to 1 solved the problem. Weird...

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