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

來源:互聯網
上載者:User
Laravel 5 基礎(十一)- Eloquent 關係

一個使用者可能有多個文章,一個文章是某個使用者書寫的,這就是關係。同樣文章中可能包含多個 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_tableRolled back: 2014_10_12_100000_create_password_resets_tableRolled back: 2014_10_12_000000_create_users_tableNothing to rollback.Migrated: 2014_10_12_000000_create_users_tableMigrated: 2014_10_12_100000_create_password_resets_tableMigrated: 2015_03_28_050138_create_article_tableMigrated: 2015_03_28_051200_add_excerpt_to_articels_table

現在讓我們使用 tinker 來建立一個使用者。

php artisan tinkerPsy Shell v0.4.1 (PHP 5.4.16 — cli) by Justin Hileman#下面是執行過程>>> $user = new App\User;=>  {}>>> $user->name = 'zhang jinglin';=> "zhang jinglin">>> $user->email = '[email protected]';=> "[email protected]">>> $user->password = bcrypt('pass');=> "$2y$10$Nbl2b9wqd.rXqKEsd3pRSOoIyFAFIhbqf71BufwDfS3Guv21SlEx2">>> $user->save();=> true>>> App\User::first()->toArray();=> [       "id"         => "1",       "name"       => "zhang jinglin",       "email"      => "[email protected]",       "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 tinkerPsy 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();=>  {       id: "1",       name: "zhang jinglin",       email: "[email protected]",       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();=>  {       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;=>  {       id: "1",       name: "zhang jinglin",       email: "[email protected]",       created_at: "2015-03-31 03:24:55",       updated_at: "2015-03-31 03:24:55"   }>>> 
1樓findgor
講下 後台圖片上傳吧。就如上傳帳戶圖片。表單編輯提交,MVC怎麼寫的。架構看不明白。
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.