Eloquent 模型关系基础概念
用户与文章之间存在典型的一对多关联:单个用户可以撰写多篇博文,而每篇博文仅归属于一位作者。同理,文章与标签之间也具备多对多或一对多的映射特性,即一篇文章可标记多个 TAG,且同一 TAG 可被多篇不同文章引用。
项目中已存在 User.php 用户模型,其结构较为简洁。为实现通过 $user->articles() 直接获取该用户所有文章的功能,需对 User 模型进行相应调整。
public function articles() {
return $this->hasMany('App\Article');
}
上述操作仅完成了关联关系的一端(User 端),还需处理另一端(Article 端)。目标是支持通过 $article->user 访问文章所属的用户信息,因此需要修改 Article 模型。
public function user() {
return $this->belongsTo('App\User');
}
当前数据库架构中,文章表尚未包含指向用户表的外键字段,必须补充此设置。具体操作涉及编辑 create_article_table.php 迁移文件。
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
//指定外键列
$table->integer('user_id')->unsigned();
$table->string('title');
$table->text('body');
$table->timestamp('published_at');
$table->timestamps();
//生成外键
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
由于项目处于开发阶段且未正式部署上线,可直接修改现有的数据库迁移脚本,执行回滚后重新迁移即可生效;若在生产环境中,则应创建新的迁移文件来变更表结构。
php artisan migrate:refresh
#输出信息
Rolled back: 2026_03_28_050138_create_article_table
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_000000_create_users_table
Nothing to rollback.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2026_03_28_050138_create_article_table
Migrated: 2026_03_28_051200_add_excerpt_to_articels_table
接下来利用 tinker 交互式环境创建一个测试用的用户实例。
php artisan tinker
Psy Shell v0.4.1 (PHP 5.4.16 — cli) by Justin Hileman
#下面是执行过程
>>> $user = new App\User;
=> {}
>>> $user->name = 'zhang jinglin';
=> "zhang jinglin"
>>> $user->email = 'zjl@example.com';
=> "zjl@example.com"
>>> $user->password = bcrypt('pass');
=> "$2y$10$Nbl2b9wqd.rXqKEsd3pRSOoIyFAFIhbqf71BufwDfS3Guv21SlEx2"
>>> $user->save();
=> true
>>> App\User::first()->toArray();
=> [
"id" => "1",
"name" => "zhang jinglin",
"email" => "zjl@example.com",
"created_at" => "2026-03-31 03:24:55",
"updated_at" => "2026-03-31 03:24:55"
]
>>>
为使新发布的文章能正确关联到指定用户,暂时在 form_partial.blade.php 视图中隐藏一个用户 ID 输入框,仅作临时调试用途。
复制代码 代码如下: {{--临时处理--}} {!! Form::hidden('user_id', 1) !!}
同时需更新模型的 $fillable 属性,以允许批量赋值(Mass Assignment)操作中包含 user_id 字段。
protected $fillable = [
'title',
'body',
'published_at',
'user_id' //临时设置
];
完成文章添加后,再次使用 tinker 检查数据状态及关联情况。
php artisan tinker
Psy Shell v0.4.1 (PHP 5.4.16 — cli) by Justin Hileman
>>> App\Article::first()->toArray();
=> [
"id" => "1",
"user_id" => "1",
"title" => "User 1 Article",
"body" => "User 1 Body",
"published_at" => "2026-03-31 08:00:00",
"created_at" => "2026-03-31 04:17:58",
"updated_at" => "2026-03-31 04:17:58",
"excerpt" => null
]
#获取用户
>>> $user = App\User::first();
=> {
id: "1",
name: "zhang jinglin",
email: "zjl@example.com",
created_at: "2026-03-31 03:24:55",
updated_at: "2026-03-31 03:24:55"
}
#获取用户文章
>>> $user->articles()->toArray();
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::toArray()'
>>> $user->articles->toArray();
=> [
[
"id" => "1",
"user_id" => "1",
"title" => "User 1 Article",
"body" => "User 1 Body",
"published_at" => "2026-03-31 08:00:00",
"created_at" => "2026-03-31 04:17:58",
"updated_at" => "2026-03-31 04:17:58",
"excerpt" => null
]
]
#为什么使用 $user->articles 而不是 #user->articles()?
#事实上,$user->articles()返回的是关系,如果你想用 articles() 你需要这样用
>>> $user->articles()->get()->toArray();
=> [
[
"id" => "1",
"user_id" => "1",
"title" => "User 1 Article",
"body" => "User 1 Body",
"published_at" => "2026-03-31 08:00:00",
"created_at" => "2026-03-31 04:17:58",
"updated_at" => "2026-03-31 04:17:58",
"excerpt" => null
]
]
#你只能使用 articles() 来进行下一步的工作,比如下面的查询
$user->articles()->where('title', 'User 1 Article')->get();
#我们也可以通过 article 获取 user
>>> $article = App\Article::first();
=> {
id: "1",
user_id: "1",
title: "User 1 Article",
body: "User 1 Body",
published_at: "2026-03-31 08:00:00",
created_at: "2026-03-31 04:17:58",
updated_at: "2026-03-31 04:17:58",
excerpt: null
}
>>> $article->user;
=> {
id: "1",
name: "zhang jinglin",
email: "zjl@example.com",
created_at: "2026-03-31 03:24:55",
updated_at: "2026-03-31 03:24:55"
}
>>>
以上所述就是本文的全部内容了,希望大家能够喜欢。