我有以下数据库:
CREATE TABLE users
(
id BIGINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
);
CREATE TABLE likes
(
id BIGINT NOT NULL AUTO_INCREMENT,
user_id BIGINT,
idea_id BIGINT,
PRIMARY KEY (id)
);
CREATE TABLE ideas
(
id BIGINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
);
用户模型:
// --------------------------------------------------------------------
// Relationships
// --------------------------------------------------------------------
public $has_many = array( 'like' , 'idea' , 'comment' );
// --------------------------------------------------------------------
// Validation
// --------------------------------------------------------------------
var $validation = array(
'username' => array(
'label' => 'Username',
'rules' => array('required', 'trim', 'unique', 'min_length' => 3 )
),
'password' => array(
'label' => 'Password',
'rules' => array('required', 'trim', 'min_length' => 3 ,'encrypt' )
)
);
理念模型:
public $has_one = array('user');
public $has_many = array('like');
// --------------------------------------------------------------------
// Validation
// --------------------------------------------------------------------
public $validation = array(
'user' => array(
'rules' => array('required')
)
);
喜欢模特:
// Relationships
// --------------------------------------------------------------------
public $has_one = array( 'user' , 'idea' );
// --------------------------------------------------------------------
// Validation
// --------------------------------------------------------------------
var $validation = array(
'user' => array(
'rules' => array('required', 'unique_pair' => 'idea' )
),
'idea' => array(
'rules' => array('required')
)
);
喜欢控制器
$idea = new Idea(1);
$user = new User(1);
$like = new Like();
if( !$like->save( array( $idea , $user ) ) )
{
echo $like->error->all;
}
else
{
echo "ok";
}
问题在于我总是很好,喜欢的内容会保存在数据库中,并且无法验证。
我想要的是让两个字段(user_id,idea_id)唯一
答案 0 :(得分:0)
在模型中添加$model
和$table
属性,这支持关系。之后,请验证您的foreign keys
。请记住模型名称的单数和表名的复数。
public $model = 'user';
public $table = 'users';
....
public function __construct($id = NULL) {
parent::__construct($id);
}