laravel创建数据库和model文件

本篇博客与下面的博客是为下面博客的增删改查做准备,首先需要创建好表并创建相应的model。

创建表:

CREATE TABLE `student` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL DEFAULT '',
`age` tinyint(3) NOT NULL DEFAULT '0',
`sex` tinyint(3) NOT NULL DEFAULT '0',
`created_at` int(11) NOT NULL DEFAULT '0',
`updated_at` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

创建model,创建目录为app\Models,创建的文件名为Student.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{

    //指定表名
    protected $table = 'student';

    //指定主键
    protected $primaryKey = 'id';

    //指定允许批量赋值的字段(使用ORM操作数据时必须指定可赋值的字段,否则报错)
    protected $fillable = ['name', 'age', 'sex'];

    //自动维护时间戳
    public $timestamps = true;

    //指定时间为unix时间戳
    public function getDateFormat() {
        return time();
    }

    //查询出的时间戳不做任何处理
    public function asDateTime($value)
    {
        return $value;
    }

    //避免转换时间戳为字符串
    public function fromDateTime($value)
    {
        return empty($value)?$value:$this->getDateFormat();
    }

}

 

更多请查看laravel手册:https://learnku.com/docs/laravel/8.x/eloquent/9406

 

【版权申明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权) https://www.cnblogs.com/facetwitter/p/15777402.html

posted @ 2022-01-08 07:42  saneim  阅读(435)  评论(0编辑  收藏  举报