Laravel 5 基礎(十一)- Eloquent 關係

一個用戶可能有多個文章,一個文章是某個用戶書寫的,這就是關係。一樣文章中可能包含多個 TAG,而一個 TAG 可能關聯多個文章。php

在項目中,咱們已經有了 User.php,也就是用戶模型,查看一下,至關簡單。咱們但願直接使用 $user->articles() 的形式獲取所有文章,讓咱們修改 user 模型:html

public function articles() {
        return $this->hasMany('App\Article');
    }

可是咱們僅僅完成了關係中的一端,讓咱們來處理另外一端。咱們但願的形式是 $article->user() ,讓咱們修改 article 模型。數據庫

public function user() {
        return $this->belongsTo('App\User');
    }

在咱們的數據庫中,文章模型沒有用戶的外鍵,咱們須要設置,修改 create_article_table.phpbash

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');
        });

由於咱們只是在開發階段,尚未上線運行,咱們能夠直接修改數據庫遷移文件,回滾而後遷移便可,可是若是上線運行的話,應該新建一個遷移。ui

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 來建立一個用戶。this

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,只是暫時:code

{{--臨時處理--}}
{!! Form::hidden('user_id', 1) !!}

同時要修改模型的 $fillabel 屬性,以便咱們的 Mass Assisment。orm

protected $fillable = [
        'title',
        'body',
        'published_at',
        'user_id' //臨時設置
    ];

OK,添加一個文章。咱們使用 tinker 來查看一下。htm

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"
   }
>>>
相關文章
相關標籤/搜索