laravel学习笔记(一)通过tinker方便的调试数据库
一,factory模型工厂
1,连接数据库执行migrate命令创建表
php artisan migrate
Migration table created successfully.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
进入laravel自带的tinker,来快捷的调试数据库数据
php artisan tinker

通过工厂创建两个用户
factory('App\User',2)->create()
factory接收的两个参数两个参数,第一个接收模型,第二个为创建模型的数量
然后通过create在数据库中生成随机数据

2,通过常规的方式查询数据
DB::table('users')->get()
通过DB对象找到users表,然后查询users表的所有数据

如果我们想要获取一个数组,可以使用all()命令

如果我们要获取第一个元素,那么也非常的简单
直接通过first获取数据库的第一个数据
DB::table('users')->get()->first()

我们还可以对查找的元素进行过滤,通过对first传递一个闭包的方式
DB::table('users')->get()->first(function($user){ return $user->name=="Haven Olson"; })

如图,如果找到,则返回数据,如果没有,则返回空

通过php artisan tinker可以很方便的对数据库进行调试,同时方便执行各种有用的动作,特别是当你想要测试一小段代码的时候,你无需再插入各种var_dump和die,然后还要在调试完后删掉它们,你只需要php artisan tinker就够了。