laravel8-model

MVC模型

model操作数据库,几种方式:
1、直接在类中定义:

const TABLE_NAME = 'users';
protected $table = self::TABLE_NAME;
public $timestamps = false;
在controller中使用时,就可以直接使用
$data = Dvwa::get() -> toArray(); 

2、第二种获取形式,在model中写入方法,调用数据库,使用get方法时,与其他版本不一样,

function readUser(){

 $user_name = DB::table('users')->where('user_id',1)->get(['user','password']);
 return $user_name;
}

在用get获取多个字段时,传入的是一个数组。

在controller中,通过定义对象来进行调用

 $dvwa = new Dvwa();
 $user = $dvwa -> readUser();
 return $user;

获取一列数据使用pluck方法获取:

$user_name = DB::table('users')->pluck('first_name');

此处有个前提是要在env的配置文件中把数据库指定清楚:

作者:凡二先生原文地址:https://segmentfault.com/a/1190000041369731

%s 个评论

要回复文章请先登录注册