0
votes

I'm getting this error in my cakephp application

Warning (512): SQL Error: 1054: Unknown column 'Category.post_id' in 'field list' [CORE\cake\libs\model\datasources\dbo_source.php, line 684]

I'm assuming that this error was caused by how I set up relationships in the models since the error states that it was looking for 'Category.post_id', a field that doesn't exist.

Here's the category model code:

class Category extends AppModel {
   var $name = 'Category';
   var $belongsTo = 'Post';
}

and post model code:

class Post extends AppModel {
    var $name = 'Post';
    var $belongsTo = 'User';
    var $hasMany = 'Category';
}

it shows up on several methods, but here's my post index action:

function index() {
    $this->set('posts', $this->Post->find('all'));
}

Any idea how I can fix this?

3
Not unless you post the method you get the error in and your relationship.JohnP
Do you have a post_id field in the categories table?JJJ

3 Answers

0
votes

Create another table called posts_categories with columns id, post_id, category_id.

then your Post Model

class Post extends AppModel {
    public $name = 'Post';
    public $hasAndBelongsToMany = array('Category');
}

then you Category Model

class Category extends AppModel {
    public $name = 'Category';
    public $hasAndBelongsToMany = array('Post');
}
0
votes

You should establish your primary key id in your model, if it`s not the same as autogenerated is (for model post it is post_id). So if your table primary key name is 'id', your post model should be

class Post extends AppModel {
    var $name = 'Post';
    var $belongsTo = 'User';
    var $hasMany = 'Category';
    var $primaryKey = 'id';
}
-1
votes

I did not have a post_id field in my database. Added that column and my problem was solved.