laravel:访问mysql数据库(10.27.0)
一,相关文档:
https://learnku.com/docs/laravel/10.x/queries/14883
二,php代码:
1,配置.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=gonews
DB_USERNAME=yourusername
DB_PASSWORD=yourpassword
2,创建model
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan make:model News
INFO Model [app/Models/News.php] created successfully.
3,app/Models/News.php
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;class News extends Model{ use HasFactory; //定义关联的数据表 protected $table = 'news'; //定义主键 protected $primaryKey = 'news_id'; // 时间字段是否自动管理(created_at 和 updated_at字段) public $timestamps = false; //读取全部数据 public function getAll() { return $this->get()->toarray(); } //分页读取数据 public function getPage($offset,$limit){ $rows = $this->orderBy('news_id','desc')->offset($offset)->limit($limit)->get(); return $rows; }} |
4,controller中调用
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use Illuminate\Support\Facades\App;use App\extend\result\Result;use App\Models\News;class NewsController extends Controller{ //显示news列表 public function list(Request $request) { if ($request->has('p')) { $p = $request->p; if ($p == 0) { $p=1; } } else { //参数不存在时 $p=1; } $size = 10; $offset = $size * ($p - 1); $limit = $size; $model = new News(); $rows = $model->getPage($offset,$limit); return Result::Success($rows); } |
三,测试效果:

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/18/laravel-fang-wen-mysql-shu-ju-ku-10-27/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
四,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0

浙公网安备 33010602011771号