1

我有以下数据库:


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 )唯一

4

1 回答 1

0

在模型中添加$model$table属性,这支持关系。之后,验证您的foreign keys. 记住模型名称的单数和表名的复数。

public $model = 'user';
public $table = 'users';

....
public function __construct($id = NULL) {
    parent::__construct($id);
}
于 2013-04-18T19:07:26.680 回答