Laravel 07 ORM文章模型

  • 创建模型命令
//模型用大写的驼峰写法  生成的模型在app下面
php artisan make:model Post

建立的model默认用laravel的规则
Post model 对应 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
>>>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容