惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
爱范儿
爱范儿
Martin Fowler
Martin Fowler
T
The Blog of Author Tim Ferriss
B
Blog RSS Feed
博客园 - 聂微东
G
GRAHAM CLULEY
Engineering at Meta
Engineering at Meta
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
WordPress大学
WordPress大学
Scott Helme
Scott Helme
AI
AI
S
Security Affairs
T
Threat Research - Cisco Blogs
M
MIT News - Artificial intelligence
T
Troy Hunt's Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
人人都是产品经理
人人都是产品经理
AWS News Blog
AWS News Blog
T
Threatpost
Cyberwarzone
Cyberwarzone
www.infosecurity-magazine.com
www.infosecurity-magazine.com
U
Unit 42
V
Vulnerabilities – Threatpost
J
Java Code Geeks
博客园 - Franky
月光博客
月光博客
Blog — PlanetScale
Blog — PlanetScale
NISL@THU
NISL@THU
D
Docker
小众软件
小众软件
N
News and Events Feed by Topic
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
A
Arctic Wolf
D
DataBreaches.Net
云风的 BLOG
云风的 BLOG
Forbes - Security
Forbes - Security
量子位
PCI Perspectives
PCI Perspectives
美团技术团队
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
I
InfoQ
Security Archives - TechRepublic
Security Archives - TechRepublic
有赞技术团队
有赞技术团队
腾讯CDC
P
Proofpoint News Feed
S
Security @ Cisco Blogs
G
Google Developers Blog
C
Cisco Blogs

博客园 - Zhangjinglin

Laravel 5 基础(十二)- 认证 Laravel 5 基础(十一)- 子视图和表单复用 Laravel 5 基础(十一)- 表单验证 Laravel 5 基础(十)- 日期,Mutator 和 Scope Laravel 5 基础(九)- 表单 Laravel 5 基础(八)- 模型、控制器、视图基础流程 Laravel 5 基础(七)- Eloquent (laravel 的ORM) Laravel 5 基础(六)- 数据库迁移(Migrations) Laravel 5 基础(五)- 环境与配置 Laravel 5 基础(四)- Blade 简介 Laravel 5 基础(三)- 向视图传送数据(续) Laravel 5 基础(三)- 向视图传送数据 Laravel 5 基础(二)- 路由、控制器和视图简介 Laravel 5 基础(一)- Laravel入门和新建项目 Android 随机铃声管理器 ubuntu netbeans 字体解决 Mac OS 10.6 原版安装 git 强制恢复到某一版本 混乱中生存
Laravel 5 基础(十一)- Eloquent 关系
Zhangjinglin · 2015-04-05 · via 博客园 - Zhangjinglin

一个用户可能有多个文章,一个文章是某个用户书写的,这就是关系。同样文章中可能包含多个 TAG,而一个 TAG 可能关联多个文章。

在项目中,我们已经有了 User.php,也就是用户模型,查看一下,相当简单。我们希望直接使用 $user->articles() 的形式获取全部文章,让我们修改 user 模型:

    public function articles() {
        return $this->hasMany('App\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: 2015_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: 2015_03_28_050138_create_article_table
Migrated: 2015_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;
=> <App\User #000000007f1ad61a000000006497cc4f> {}
>>> $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" => "2015-03-31 03:24:55",
       "updated_at" => "2015-03-31 03:24:55"
   ]
>>> 

现在我们需要新发布的文章和用户关联,我们暂时先修改 form_partial.blade.php 来隐藏一个用户id,只是暂时:

{{--临时处理--}}
{!! Form::hidden('user_id', 1) !!}

同时要修改模型的 $fillabel 属性,以便我们的 Mass Assisment。

	protected $fillable = [
        'title',
        'body',
        'published_at',
        'user_id' //临时设置
    ];

OK,添加一个文章。我们使用 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" => "2015-03-31 08:00:00",
       "created_at"   => "2015-03-31 04:17:58",
       "updated_at"   => "2015-03-31 04:17:58",
       "excerpt"      => null
   ]

#获取用户
>>> $user = App\User::first();
=> <App\User #0000000051cbb9d70000000073e11a3e> {
       id: "1",
       name: "zhang jinglin",
       email: "zjl@example.com",
       created_at: "2015-03-31 03:24:55",
       updated_at: "2015-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" => "2015-03-31 08:00:00",
           "created_at"   => "2015-03-31 04:17:58",
           "updated_at"   => "2015-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" => "2015-03-31 08:00:00",
           "created_at"   => "2015-03-31 04:17:58",
           "updated_at"   => "2015-03-31 04:17:58",
           "excerpt"      => null
       ]
   ]
   
#你只能使用 articles() 来进行下一步的工作,比如下面的查询

$user->articles()->where('title', 'User 1 Article')->get();

#我们也可以通过 article 获取 user

>>> $article = App\Article::first();
=> <App\Article #0000000051cbb9d60000000073e11a3e> {
       id: "1",
       user_id: "1",
       title: "User 1 Article",
       body: "User 1 Body",
       published_at: "2015-03-31 08:00:00",
       created_at: "2015-03-31 04:17:58",
       updated_at: "2015-03-31 04:17:58",
       excerpt: null
   }
>>> $article->user;
=> <App\User #0000000051cbb92d0000000073e11a3e> {
       id: "1",
       name: "zhang jinglin",
       email: "zjl@example.com",
       created_at: "2015-03-31 03:24:55",
       updated_at: "2015-03-31 03:24:55"
   }
>>>