laravel构造器及模型
home.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Article;
// 后台主页
class Home extends Controller{
// 查询多条记录
// get()
// get()->all()数组
public function list(){
$res = DB::table('article')->get()->all();
echo '<pre>';
print_r($res);
}
// 指定查询字段select
// 条件where('cate_id','=',5), '='可省略
// and使用where()->where()
// or使用where()->orWhere()
public function selectlist(){
$res = DB::table('article')->select('cate_id as cid','title')->where('cate_id',5)->get()->all();
echo '<pre>';
print_r($res);
}
// like查询
// tosql可查看sql语句,?是点位符
public function likes(){
$res = DB::table('article')->where('title','like','%5%')->where('cate_id',5)->tosql();
echo '<pre>';
print_r($res);
}
// where in查询
public function wherein(){
$res = DB::table('article')->whereIn('cate_id',[1,5,7])->get()->all();
echo '<pre>';
print_r($res);
print_r($res[0]->title);
}
// 连表查询
public function joins(){
$res = DB::table('article')->join('users','users.id','=','article.uid')->select('article.title','users.username as nickname')->get()->all();
echo '<pre>';
print_r($res);
}
// 平均avg,最大max,最小min,计数count
public function pvs(){
$res = DB::table('article')->avg('pv');
//$res = DB::table('article')->max('pv');
//$res = DB::table('article')->min('pv');
//$res = DB::table('article')->count();
$res = (int)$res;
echo '<pre>';
print_r($res);
}
// 增加数据
public function insert2(){
$data = [];
$data[]= array('uid'=>2,'cate_id'=>7,'title'=>'insert测试5','pv'=>0);
$data[]= array('uid'=>1,'cate_id'=>6,'title'=>'insert测试4','pv'=>0);
$res = DB::table('article')->insert($data);
echo '<pre>';
var_dump($res);
}
// 增加数据并获取ID
public function insert3(){
$data= array('uid'=>1,'cate_id'=>8,'title'=>'insert测试7','pv'=>0);
$res = DB::table('article')->insertGetId($data);
echo '<pre>';
var_dump($res);
}
// 修改数据
public function update2(){
$res = DB::table('article')->whereIn('id',[10,11])->update(array('title'=>'update测试'));
echo '<pre>';
var_dump($res);
}
//删除
public function delete2(){
$res = DB::table('article')->whereIn('id',[10,12])->delete();
echo '<pre>';
var_dump($res);
}
//模型
public function mymodels(Article $article){
$res = $article->get()->toArray();
echo '<pre>';
print_r($res);
}
}
创建模型(article.php)
在powershell中
H:\phpstudy_pro\www\laravel7> php artisan make:model Article
article.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
//指定表名,不然默认找名字为“articles”的表
protected $table= 'article';
}