- 创建模型命令
//模型用大写的驼峰写法 生成的模型在app下面
php artisan make:model Post
建立的model默认用laravel的规则
Postmodel 对应posts表
自定义的表 要设置$table如:protected $table = "posts2"
//默认对应表 => posts
class Post extends Model
{
//自定义对应表设置
// protected $table = 'posts2';
}
- thiner的使用 :可以直接操作model测试的工具
- 启动命令
php artisan tinker
- 启动命令
1、新增示例
>>> $post = new \App\Post();
=> App\Post {#2848}
>>> $post->title = "this is post22"
=> "this is post22"
>>> $post->content = "this is post22 content"
=> "this is post22 content"
>>> $post->save();
=> true
>>>
2、查询示例
find方法只能用在主键上
>>> \App\Post::find(1);
=> App\Post {#2851
id: 1,
title: "this is post11",
content: "this is post11 content",
user_id: 0,
created_at: "2018-11-09 08:17:40",
updated_at: "2018-11-09 08:17:40",
}
>>>
// first()方法返回的是一个对象
>>> \App\Post::where("title","this is post11")->first();
=> App\Post {#2852
id: 1,
title: "this is post11",
content: "this is post11 content",
user_id: 0,
created_at: "2018-11-09 08:17:40",
updated_at: "2018-11-09 08:17:40",
}
>>>
//get方法返回的是一个Collection对象数组
>>> \App\Post::where("title","this is post11")->get();
=> Illuminate\Database\Eloquent\Collection {#2844
all: [
App\Post {#2855
id: 1,
title: "this is post11",
content: "this is post11 content",
user_id: 0,
created_at: "2018-11-09 08:17:40",
updated_at: "2018-11-09 08:17:40",
},
],
}
>>>
3、修改示例
//先find(id) 再赋值字段,然后save()
>>> $post = \App\Post::find(2)
=> App\Post {#2851
id: 2,
title: "this is post22",
content: "this is post22 content",
user_id: 0,
created_at: "2018-11-09 16:20:20",
updated_at: "2018-11-09 16:20:20",
}
>>> $post->title = "this is update post22"
=> "this is update post22"
>>> $post->save()
=> true
>>>
4、删除
//先find(id) 再delete()
>>> $post = \App\Post::find(2)
=> App\Post {#2855
id: 2,
title: "this is update post22",
content: "this is post22 content",
user_id: 0,
created_at: "2018-11-09 16:20:20",
updated_at: "2018-11-09 16:32:12",
}
>>> $post->delete()
=> true
>>>