CakePHP Relationship Errors
I'm getti开发者_如何学运维ng 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?
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');
}
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';
}
I did not have a post_id field in my database. Added that column and my problem was solved.
精彩评论