iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 19
0
Modern Web

PHP laravel的邂逅系列 第 19

DAY19-laravel:Eloquent ORM 一對多

資料表會有users、roles、role_user這三個資料表。
users:定義使用者的表
roles:定義使用者權限的表
role_user:上面兩個表的中介

先在users資料表中新增兩個使用者,這樣我們就有使用者了

在新增一個role的model,定義使用者的權限,在model裡面多新增一個name的欄位,在資料表裡面新增一個admin和normal的資料。

php artisan make:model Role -m
class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

role資料表像下圖一樣

接著在新增把user和role的表,連接起來的user_role的表,在user_role的migration的裡面多新增兩個欄位,分別是user_id和role_id,這樣才能讓user找到對應的role資料。

php artisan make:migration create_users_roles_table --create=role_user
class CreateUsersRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('role_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }
}

在User.php model中新增一個function,在裡面呼叫belongsToMany的方法,可以讓user找到對應的role。

public function roles(){
        return $this->belongsToMany('App\Role');
    }

在route新增下面的程式碼就能讓User找到對應的role資料

Route::get('/user/{id}/role',function($id){
    $user = User::find($id);

    foreach($user->roles as $role){
        return $role->name;
    }
});

上一篇
DAY18-laravel:Eloquent ORM 一對一
下一篇
DAY20-laravel:Eloquent ORM 多對多
系列文
PHP laravel的邂逅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
datomon
iT邦新手 5 級 ‧ 2018-08-30 21:26:22

這篇寫到多對多的內容了@@

我要留言

立即登入留言