Laravel学习日记-基本模型
in LaravelPHP with 0 comment

Laravel学习日记-基本模型

in LaravelPHP with 0 comment

常规

位置

一般放在/app下,命名空间是App,
也可放在其他文件夹,但要保持命名空间一致。

命名

一般去掉表名后缀 s 即为模型名称,
比如表名为 users ,那么模型名称应为 User
也可自定义:
例如表名为 user ,并没有s后缀,
那么再模型中定义一个 protect 属性:

protected $table = 'user';

继承自

继承自 IlluminateDatabaseEloquentModel
应声明:

use Illuminate\Database\Eloquent\Model;

自动生成和实例化

Model 可以手写,可以也用 artisan 命令行工具生成.
例 : php artisan make:model Msg

实例化:

$model = new App\Xxx(); // 得到 Xxxs 表的 Model, 且不与表中任何行对应 .
$model = APP\Xxx::find(4); // 静态方法调用, 得到 Xxxs 表的 Model, 且与 $id=4 的数据对应 .

基本CURD

public function add() {
    $msg = new \App\Msg();
    $msg->title = $_POST['title'];
    $msg->content= $_POST['content'];
    return $msg->save() ? 'OK' : 'fail';
}

先找到, 然后删

public function del($id) {
    $msg = Msg::find($id);
    return $msg->delete() ? 'ok' : 'fail';
}

用条件选择直接删:

public function del($id) {
    return Msg::where('id',$id)->delete()? 'ok' : 'fail';
} 

public function up($id) {
    if( empty($_POST) ) {
        $msg = Msg::find($id);
        return view('msg.up',['msg'=>$msg]);
    }else {
        $msg = Msg::find($id);
        $msg->title = $_POST['title'];
        $msg->content= $_POST['content'];return $msg->save() ? 'OK' : 'fail';
    }
}

查单行 : find()first()

// 按主键查
Msg::find($id) // 按主键查
// 按 where 条件查具体那一条
Msg::where('id','>',3)->first();

查多行 : all()get()

// 无条件查所有行 . select 列 1, 列 2 from msgs;
Msg::all(['列1','列2']);// 按条件查多行
// 按条件查多行
Msg::where('id','>',2)->get([' 列 1',' 列 2']); //数组选列
Msg::where('id','>',2)->select('title','content')->get(); //字符串选列

查询更多操作

排序 :

// select ... where id > 2 order by id desc;
Msg::where('id','>',2)->orderBy('id','desc')->get();

限制条目

// select .. where id>2 order by id desc limit 2,1;

//跳过两行 取一行

Msg::where('id','>',2)->orderBy('id','desc')->skip(2)->take(1)->get();

统计:

Msg::count();
Msg::avg('id');
Msg::min('id');
Msg::max('id');
Msg::sum('id');

更加复杂的查询:
http://laravel-china.org/docs/5.1/queries

约定

id 的约定
表名的约定
默认表名为 Model 名 + s,如果不想这样做, 可以通过的 model 类的 table 属性来指定表名.
例:

class XxModel extends Model {
    protected $table = 'yourTableName';
}

Model 默认 认为,每张表都有一个叫做id的主键,
如果向通过其他字段名来设置主键, 可以通过primaryKey属性来指定主键列名

class XxModel extends Model {
    protected $primaryKey = 'Xx_id'; //注意: Key 首字母大写
}

created_at,updated_at字段的约定
Model 默认有这2个字段,且在更新行时,会自动帮你更新这两个字段.
如果不想这样,甚至不想要这2个字段,
可以在创建迁移文件后, 删除 $table->timestamps();
然后, 设置 model 的 timestamps 属性设为 false

class XxModel extends Model {
    public $timestamps = false;
}
Responses
icon_mrgreen.gificon_neutral.gificon_twisted.gificon_arrow.gificon_eek.gificon_smile.gificon_confused.gificon_cool.gificon_evil.gificon_biggrin.gificon_idea.gificon_redface.gificon_razz.gificon_rolleyes.gificon_wink.gificon_cry.gificon_surprised.gificon_lol.gificon_mad.gificon_sad.gificon_exclaim.gificon_question.gif