技术&日志

Laravel-Model

Laravel – Model – Eloquent

在创建Laravel之后, 并没有Model文件夹.

创建一个Model

方法一: 通过命令方式创建

php artisan make:model Member #默认创建的文件位置 app/Member.php
php artisan make:model Http/Member #指定路径目录创建 app/Http/Member
php artisan make:model -m Test #创建一个可迁移的表, 会创建两个文件 app/Test.php database/migrations/文件.php
php artisan migrate #运行所有未运行过的迁移 
php artisan migrate --path=/database/migrations/single #指定某个文件

PS: 若需要删除就找到文件直接删除. 通过php artisan help make:model 未找到命令删除方法.

方法二: 手动创建

<?php
# 创建于app/Member
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
protected $table = 'user'; #表名

public function lists()
{
return self::all(); #获取所有的数据
}
}

Model常用属性

protected $table # 设置当前模块的表

关于可迁移的模型

默认字段, 自增长,主键的ID 与时间字段

更多设置 -> \vendor\laravel\framework\src\Illuminate\Database\Schema\Blueprint.php

#文件位置 database/migrations/{time}_create_tests_table.php
public function up()
{
Schema::create('tests', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 20)->comment('用户名');
$table->string('password');
$table->timestamps();
});
}

增删改查

#文件 app/Test.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
protected $fillable = [
'name', 'password', #定义可入库的字段
];
}
#文件 app/Http/Controllers/Test.php
<?php

namespace App\Http\Controllers;
use App\Test as M;
class TestController extends Controller
{
/**
* 数据入库
*/
public function add(M $model)
{
$data = ['name' => '测试用户名', 'password' => '123123'];
$model->fill($data)->save();
$lastid = $model->id;
echo $lastid;
}
/**
* 数据更新
*/
public function renew(M $model)
{
$data = ['name' => '更新用户名', 'password' => '123123'];
$result = $model->where(['id' => 1])->update($data);
var_dump($result);
}
/**
* 数据查询
* DB类可以使用的 model中也可以使用
* - value('field') 获取某个字段的值
* - pluck('field') 获取某列的所有值
*/
public function inquire(M $model)
{
$info = $model->find(1);
#var_dump($info->toArray());
$list = $model::paginate(5);
#var_dump($list->toArray());
}
/**
* 数据删除
*/
public function del(M $model)
{
$result = $model->where(['id' => 2])->delete();
var_dump($result);
}
}

日志记录

Q: SQLSTATE[HY000] [2002] Connection refused (SQL: select * from member)
A: 在docker容器中不要使用127.0.0.1 需使用docker-compose.yml里数据库定义的服务名称. 更多>>


Q: Field xxxdoesn’t have a default value
A: laravel中mysql默认使用了严格的验证方式, 在配置文件中strict设置为false. Config/database.php 'strict' => false, 更多>>

相关资料

官方文档-模型基本使用