ORM 类(eloquent)
- 查询结果为空,或者通过关联关系取出的空结果判断(坑:用empty)
例如:
$goodsCategory = GoodsCategory::with('goodses')->where(.....)->.....->get(); // 无结果
if(!empty($goodsCategory)){
echo 'has data';
} else {
echo 'no data';
}
** 大家觉得会输出什么?
结果出乎我的想象,当没有查询结果时,输出结果是: has data
之前一直以为返回的结果是一个数组对象,所以如果是空数组,empty 是怎么都可以判断到的,实在没法了,只有去看API了。
结果是:返回的结果属于:Illuminate\Database\Eloquent\Collection Object
但是如果是first()或者find(),查询结果为单条记录时,返回的对象又是:model
这些终于明白了。
返回的结果并不是数组对象,而是Illuminate\Database\Eloquent\Collection Object,所以empty无效,然后在这个collection 类里发现了一个可以判断是否为空的方法
if($goodsCategory->isEmpty()){
echo "no data";
} else {
echo "has data";
}
输出结果就正常了。
表单验证
- 表单验证:正则表达式
** 问题: 真正中含有”|”符号的时候,之前的写法:
'number' => 'required|regex:^(0?|[1-9]\d*)(\.\d{0,2})?$',
这样写一定报错,因为正则中包含“|”规则分隔符
引用:
注意: 当使用regex模式时,您必须使用数组来取代”|”作为分隔,尤其是当正规表示式中含有”|”字串。
所以正确的写法应该为:
'number' => array('required', 'regex:^(0?|[1-9]\d*)(\.\d{0,2})?$'),
数据迁移(migrate)
- 添加外键时报错
情况如下:
// users 迁移代码
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
// 关联表 orders 迁移代码(有问题的)
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->index();
$table->decimal('price');
$table->tinyInteger('status');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
如上代码,在执行迁移时会报错:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `orders` add constraint orders_user_id_foreign foreign key (`
user_id`) references `users` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
错误原因和解决办法:
原因: increments 自动增长ID,类型不是unsigned,而外键呢又必须是unsigned
解决办法:
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index();
$table->decimal('price');
$table->tinyInteger('status');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
外键字段用unsignedInteger方法来添加。