【问题标题】:Datamapper ORM / Codeigniter - - - validate relationDatamapper ORM / Codeigniter - - - 验证关系
【发布时间】:2012-08-26 21:37:38
【问题描述】:

我有以下数据库:


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)都是唯一的

【问题讨论】:

    标签: php codeigniter codeigniter-datamapper


    【解决方案1】:

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

    public $model = 'user';
    public $table = 'users';
    
    ....
    public function __construct($id = NULL) {
        parent::__construct($id);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多