Laravel 爬过的坑

ORM 类(eloquent)

  1. 查询结果为空,或者通过关联关系取出的空结果判断(坑:用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";
}

输出结果就正常了。

表单验证

  1. 表单验证:正则表达式
    ** 问题: 真正中含有”|”符号的时候,之前的写法:
'number' => 'required|regex:^(0?|[1-9]\d*)(\.\d{0,2})?$',

这样写一定报错,因为正则中包含“|”规则分隔符
引用:

注意: 当使用regex模式时,您必须使用数组来取代”|”作为分隔,尤其是当正规表示式中含有”|”字串。
所以正确的写法应该为:

'number' => array('required', 'regex:^(0?|[1-9]\d*)(\.\d{0,2})?$'),

数据迁移(migrate)

  1. 添加外键时报错
    情况如下:
// 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方法来添加。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟没翅膀

你的打赏是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值