laravel-model

        一.作用:一个model即一条db数据

 

   二.例子:如下所示, 继承Model

 1 class testModel extends Model {
 2     
 3     protected $connection = 'test';
 4     
 5     protected $table      = 'test';
 6     
 7     //设置可填充数据
 8     protected $fillable = [
 9         'id',
10         'name',
11         'cus_val',
12         'time',
13         'a->b',
14         'a->c',
15         'arr',
16     ];
17     
18     //指定时间格式
19     protected $dates = [
20         'time'
21     ];
22 
23     //指定数据类型, 获取时会转为相应类型
24     protected $casts = [
25         'name' => 'string',
26     ];
27 
28     //指定builder的relation, 会调用相应方法
29     protected $with = [
30     ];
31 
32     
33     public function test() {
34         $test2 = new test2Model();
35         $builder = test2Model::query();
36         return new Illuminate\Database\Eloquent\Relations\HasMany($builder, $this, $test2->getKeyName(), $this->getKeyName());
37     }
38     
39     function touchTest2 () {
40         
41     }
42     
43     
44     public function setCusValAttribute($value) {
45         echo 'throuth setCusValAttribute' . PHP_EOL;
46         $this->attributes['cus_val'] = $value;
47     }
48 }
49 
50 class test2Model extends Model {
51     protected $connection = 'test';
52     
53     protected $table      = 'test2';    
54 }

 

   三.例子

  (1)参数$fillable指定可填充的数据  fillable()也可设置

 1 //(1)一般填充
 2 $o->fill(['age' => 1, 'name' => 'test']);    //构造函数也会调用fill
 3 echo $o->getAttribute('age');                //age 获取不到
 4 echo $o->getAttribute('name');
 5 
 6 //(2)自定义方法填充  存在'set'.Str::studly($key).'Attribute'  eg:setCusValAttribute
 7 $o->fill(['cus_val' => 'cusval']);
 8 echo $o->getAttribute('cus_val');
 9 
10 //(3)含-> 会转json
11 $o->fill(['a->b' => 'test']);
12 $o->fill(['a->c' => 'test2']);
13 echo $o->getAttribute('a');    //{"b":"test","c":"test2"}
14 
15 //(4)forceFill 不需指定fillable  直接填充
16 $o->forceFill(['force' => 'force']);
17 echo $o->getAttributeValue('force');

 

  (2)参数$dates指定自动格式化为时间个键值 默认含有 created_at updated_at (CREATED_AT, UPDATED_AT)

1 $o->fill(['time' => time()]);
2 echo $o->getAttribute('time');   //2020-12-28 20:03:34

  (3)参数$casts指定返回数据类型,会在返回的时候进行转换

1 $o->fill(['name' => 1]);
2 echo gettype($o->getAttribute('name'));  //sting

 

  (4)参数$with 先执行select 获取结果之后根据关联键值 执行  where in 将结果根据关联键值依次匹配

$builder = $o->newQuery();    //合入了with
$list = $builder->get(['id']);
print_r($list->toArray());die;

 

  (5) qualifyColumn 列名填充表名

1 echo (new testModel())->qualifyColumn('id');

 

  (6)newInstance($attributes = [], $exists = false)  返回个实例(本身, 带链接和table 参数传参带入) 传参可设置exists和属性

 

  (7)newFromBuilder newInstance基础上执行retrieved事件

 

  (8)newFromBuilder 复制model本身

 

  (9)newQuery  返回一个Illuminate\Database\Eloquent\Builder实例 注入db链接和model

 

  (10)newModelQuery 同qurey  没有注册$globalScopes  

 

  (11)load 为model加载relation

1 $o->forceFill([
2     'id' => 1,
3 ]);
4 $o->load(['test']);
5 print_r($o->toArray());

 

  (12)loadMissing  加载之前没有加载过的relation

1 $o->forceFill([
2     'id' => 1,
3 ]);
4 $o->load(['test']);
5 $o->loadMissing(['test:id']);   //这里并不会执行load
6 print_r($o->toArray());

 

  (13)loadCount  relation的count

1 $o->forceFill([
2     'id' => 1,
3 ]);
4 $o->loadCount(['test as count']);
5 print_r($o->toArray());

 

  (14)increment  自增n   ext标识修改别的项

1 $o->where(['id' => 1])->increment('age', 1, ['name' => 'testname']);
2 
3 //如果exists  按存在的主键查询
4 $o->forceFill([
5     'id' => 1,
6 ]);
7 $o->exists = true;
8 $o->increment('age', 1, ['name' => 'testname']);

 

  (15)decrement  同increment  自减

 

  (16)update  更新 调的save  需要exists为true

1 $o->forceFill([
2     'id' => 1,
3 ]);
4 $o->exists = true;
5 $o->update(['name' => 'aaaa']);

 

  (17)push 调save 并且调relation的save

  (18)save  不存在新增 存在并且有数据变化则更新

  (19)saveOrFail 开启事务save

  (20)destroy 删除传入的id  先查(in)后挨个删

  (21)delete 删除 需要exists

  (22)newQueryWithoutRelationships  不带relation的builder

  (23)newEloquentBuilder($query)  return new Builder($query);  Illuminate\Database\Query\Builder

  (24)newCollection(array $models = [])   return new Collection($models);

  (25)newPivot(self $parent, array $attributes, $table, $exists, $using = null)  感觉像是可以创建一个链表 返回子节点  $parent是上一个节点  db链接继承父节点  $attributes, $table, $exists用于设置子节点属性

  (26)attributesToArray  attributes转数组

  (27)relationsToArray   relatiion转数据

  (28)toArray  merger attributes和relation 转数组

  (29)toJson  toarray之后转json

  (30)getKeyName  主键  默认id

  (31)setKeyName  设置主键名

  (32)getQualifiedKeyName 主键加表名

  (33)getKeyType 主键类型

  (34)setKeyType 设置主键类型

  (35)getIncrementing 自动递增

  (36)setIncrementing 设置自动递增

  (37)getKey 获取主键值

  (38)query同newQuery 静态方法

  (40)resolveConnection($connection = null)  getConnection调用的这个方法  传的的$connection

  (41)getConnectionResolver  获取$resolver

  (42)setConnectionResolver  注入  $resolver  解决db连接问题  Illuminate\Database\DatabaseManager  Model::setConnectionResolver($app['db']);

  (43)unsetConnectionResolver unset

  (44)registerGlobalScopes 为builder注册其Scopes

1 $builder = $o->newQueryWithoutScopes();                 //没有scopes的builder
2 echo $builder->get()->count();                          //2  表里一共有两条数据
3 
4 $o::addGlobalScope('testScope', function ($builder) {   //为model加一个scope  加一个where条件
5     $builder->where('id', '=', 1);
6 });
7 
8 $o->registerGlobalScopes($builder);                     //注册到这个builder里
9 echo $builder->get()->count();                          //1  虽然没有传入条件但是因为被scope修饰了下,加上了了个where条件

 

  (45)newQueryForRestoration  加了主键where的builder  $builder = $o->newQueryForRestoration([1]);

 

  (46)fresh($with = [])  创建一个新的model  重新加载下db数据(按主键,需要exists) 加载wiht并返回

1 $freshModel = $o->newInstance(['id' => 1], true)->fresh();
2 print_r($freshModel->attributesToArray());

 

  (47)refresh()  刷新自身数据(不创建新的数据)  加载relaiton

1 $o = $o->newInstance(['id' => 1], true);
2 $o->refresh();
3 print_r($o->attributesToArray());

 

  (48)replicate(array $except = null)  属性去除了主键 create_at和update_at  和$except指定的属性

1 $o->forceFill([
2     'id'   => 1,
3     'attr' => 'test',
4 ]);
5 
6 print_r($o->replicate()->attributesToArray());

 

  (49)is($model) 对比两个model的pk table connection

1 $oback = clone $o;
2 echo $o->is($oback);

 

  (50)isNot  is 反

  (51)getConnection  echo get_class($o->getConnection());    //Illuminate\Database\MySqlConnection  mysql为例

  (50)getConnectionName echo $o->getConnectionName();

  (50)setConnection  $o->setConnection('test');

toJson  toarray之后转json

posted @ 2020-12-31 15:17  Dahouzi  阅读(355)  评论(0编辑  收藏  举报