Eloquen模型的具体使用方法

一、关联数据库中的表

class User extends Model
{
    protected $table = 'gq_user';//关联表
}

二、获取数据

class User extends Model
{
    protected $table = 'gq_user';//关联表、
    public function getdata(){
        $user = self::all();
        //获取所有的数据,数据是集合的类型,可以转换成数组 self::all()->toArray();
        $user = self::where('filed','value')->get();
        //获取到的数据是一个数组,是个二维数组,如果只有一个数据$user[0]才能取出数据
        //一般用于多个数据的取出
        $user = self::find($id);
        //用于取出where的时候是id的索引的数字 ¥id必须是id才行,唯一的值,一位数组。
         $user = self::where('active', 1)->first();
         //获取第一个数组,如果用手机号获取用户信息,手机号唯一,也用first获取用户信息,一维数组

        //也可以用self->find();self->where();$this->find();$this->where()
        //多重约束
        ->where('active', 1)
               ->orderBy('name', 'desc')
               ->take(10)
               ->get();
           //聚合查询
           where('active', 1)->count();//数量
           where('active', 1)->max('price');价格最大的数据
    }
}

三、添加数据

public function add(){
    $this->name = liu;
    $this->age = 20;
    $this->save();
}

四、修改数据

$user = $this->find($id);//获取需要修改的信息
$user->name = wang;
$user->age = 21;
$user->save();
//批量化修改
:where('active', 1)
      ->where('destination', 'San Diego')
      ->update(['delayed' => 1]);

屋、删除数据

::find(1)->delete();
或者
::destroy($id);
::where('active', 0)->delete();

六、字段隐藏、修改

class User extends Model
{
    protected $table = 'gq_user';//关联表、
    protected $hidden = ['password''phone'];//获取的数组不包括这两个字段
    protected $appends = [
        'userdata',
        'spe',
        'productname',
    ];//给数据添加一些字段
    //添加字段的方法
     public function getUserdataAttribute($value)
    {
        $user = 111111;
        return $user;//这样获取道德数据就会多一个userdata的字段,字段的值可以是数组
        get+字段名+Attribute($value) 函数命名方法,字段名驼峰命名,跟上班sppends一样
    }
    //修改获取带的字段的值,本身有Nickname这个字段,改变一下值
   //根据评论表 获取nickname 并隐去中间字
    public function getNickNamettribute($value)
    {
        $user = gqmodel('user')->find($this->user_id);
        $nickName = mb_substr($user['nickname'], 0, 1, 'utf-8') . '***' . mb_substr($user['nickname'], -1, 1, 'utf-8');
        return $nickName;
    } 
    //修改填入数据库的数据的值
    //填入的是一组数组,但是数据库不支持数组,把数组序列化一下,
     public function setDiscussImgAttribute($value)
    {
        if(empty($value)){
            $this->attributes['discuss_img'] = "0";
        }else{
            $this->attributes['discuss_img'] = serialize($value);
        }
    }
    //取出的时候反序列化一下
     return unserialize($value);//转成数组
}

模型关联
在模型中,订单表关联用户表,关联需要关联的App\Users路径加名称 user_id = id

public function user()
    {
        return $this->belongsTo('App\Users', 'user_id', 'id');
    }

猜你喜欢

转载自blog.csdn.net/weixin_42597707/article/details/81700366
今日推荐