Eloquent可零SQL完成增删改查与关联操作:需正确定义模型表名、主键及填充字段,用find、where、create等方法操作数据,并通过hasMany/belongsTo声明关联,注意fillable、timestamps等易错配置。

刚接触 Laravel,想用 Eloquent 快速查数据、存记录、建关联?不用写 SQL 也能搞定——关键在于模型定义准确、调用方法得当、避开常见坑。下面直接上手最关键的几步。
创建模型并关联表
模型是 Eloquent 的入口。运行命令生成模型文件:
-
php artisan make:model User→ 在app/Models/User.php创建基础模型 - 默认会对应
users表(类名复数);如果表名是member_info,在模型里加:protected $table = 'member_info'; - 主键不是
id?指定:protected $primaryKey = 'user_no'; - 若主键非自增整型(如 UUID),还要加:
public $incrementing = false;和protected $keyType = 'string';
基本增删改查操作
模型类本身就能发起查询,无需实例化:
- 查单条:
User::find(123)(按主键)或User::where('email', 'a@b.com')->first() - 查多条:
User::where('status', 'active')->get() - 新增一条:
User::create(['name' => '张三', 'email' => 'z@b.com'])(需在模型中设置$fillable) - 更新字段:
User::where('id', 1)->update(['status' => 'inactive'])或先查后改:$u = User::find(1); $u->status = 'pending'; $u->save(); - 删除:
User::destroy(5)或User::where('id', 5)->delete()
快速处理关联关系
比如用户有多个文章,文章属于一个用户。在 User 模型中定义:
public function posts() { return $this->hasMany(Post::class); }- 在
Post模型中定义:public function user() { return $this->belongsTo(User::class); } - 查用户及他的所有文章:
User::with('posts')->find(1)(避免 N+1 查询) - 查某篇文章和作者:
Post::with('user')->find(10) - 新建关联记录更简单:
$user->posts()->create(['title' => '新文章'])
注意几个易错点
新手常卡在这几处,提前留意能省大量调试时间:
-
create()要求模型中声明可批量赋值字段:protected $fillable = ['name', 'email'];,否则报错 -
get()返回的是Collection对象,不是数组;要转数组用->toArray(),要取首项用->first() - 时间字段(
created_at/updated_at)默认启用;不需要?在模型中设:public $timestamps = false; - 数据库字段含下划线(如
last_login_at),Eloquent 默认映射为驼峰(lastLoginAt);读写都自动转换,无需额外处理

















