我第一次使用Laravel 4为客户构建web应用程序。我有两个表,User
和Zone
,它们之间有关系。
特别是,这是(简化的)User
Schema::create('users', function($table) {
$table->increments('id');
$table->string('name');
$table->enum('role', array('type1', 'type2', 'type3')->default('type1');
$table->integer('zone_id')->nullable();
});
这是Zone
Schema::create('zones', function($table) {
$table->increments('id');
$table->string('name');
});
用户可以有零个或一个区域,这就是zone_id
可以为null的原因。但是,只有当它们的role
列的值为type2
或type3
时,它们才可以有一个区域,而如果role
是type1
则不能。
这些是我的型号
// models/User.php
class User extends Eloquent {
public function zone() {
return $this->belongsTo('Zone');
}
}
// models/Zone.php
class Zone extends Eloquent {
public function users() {
return $this->hasMany('User');
}
}
我不知道如何在模型中添加role
条件。
事实上,我正在写一个失败的测试:
class UserTest extends TestCase {
public function testUserInZoneMustHaveASpecificRole() {
$zone = FactoryMuff::create('Zone');
$user = FactoryMuff::create('User');
// $user, by default has role == 'type1'
// This should pass, because I shouldn't be able to
// associate a role=='type1' user to a zone
$this->assertFalse($zone->users()->save($user)->save());
}
}
你能帮我一下吗?由于我的客户要求,我在应用程序的许多部分都面临这个问题。
谢谢。
我建议您查看"laravelbook/heart"
https://github.com/laravelbook/ardent
这个对基本Eloquent Model类的扩展正是你想要的——它在允许保存之前会自动验证。
您不需要手动调用validate()
,而只需要像这样调用save()
:
if ( $model->save() ) {
echo "yay, it was all ok"
} else {
echo "boo, we failed to save";
}
您可以像通常使用Laravel一样创建验证规则,但Ardent在为您处理这些规则方面要聪明得多。