close
//下指令
php artisan make:model Video -m
php artisan make:model Tag -m
php artisan make:model Taggable -m
//創造video表格
        Schema::create('videos', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

//創造tag表格
        Schema::create('tags', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

//創造taggable表格
        Schema::create('taggables', function (Blueprint $table) {
            $table->integer('tag_id');
            $table->integer('taggable_id');
            $table->string('taggable_type');
        });
//下指令
php artisan migrate
	//檔案:app/post.php
	public function tags(){
		return $this->morphToMany('App\Tag','taggable');
	}

    //檔案:app/tag.php
    public function posts(){
    	return $this->morphedByMany('App\Post','taggable');
    }
    public function videos(){
    	return $this->morphedByMany('App\Video','taggable');
    }
//增加與修改一些資料
INSERT INTO `videos` (`id`, `name`, `created_at`, `updated_at`) 
VALUES (NULL, 'php相關影片.mov', NULL, NULL), (NULL, 'js相關影片.mov', NULL, NULL);

INSERT INTO `tags` (`id`, `name`, `created_at`, `updated_at`) 
VALUES (NULL, 'php', NULL, NULL), (NULL, 'javascript', NULL, NULL);

INSERT INTO `taggables` (`tag_id`, `taggable_id`, `taggable_type`) 
VALUES ('1', '1', 'App\\Video'), 
('2', '1', 'App\\Post');

UPDATE `posts` SET `title` = 'js標題1', `content`='js內容1',`created_at` = NULL, `updated_at` = NULL, `deleted_at` = NULL WHERE `posts`.`id` = 1;

UPDATE `posts` SET `title` = 'php標題1', `content`='php內容1', `created_at` = NULL, `updated_at` = NULL, `deleted_at` = NULL WHERE `posts`.`id` = 2;
//檔案:routes/web.php

Route::get('post/tag', function() {
    $post=Post::find(1);
    foreach ($post->tags as $tag) {
        echo $tag->name ;
    }
});

瀏覽器輸入:post/tag

出現編號1的貼文對應到的tag的名字

//檔案:routes/web.php

use App\Tag;

Route::get('tag/post', function() {
    $tag=Tag::find(2);
    foreach ($tag->posts as $post) {
        echo $post->title;
    }
});

瀏覽器輸入:tag/post

出現編號2的標籤對應到的貼文的標題

(由於taggables表格內,tag_id第二個對應到taggable_type是App\Post,所以才能顯示post物件裡面的屬性)

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Jerry 的頭像
    Jerry

    Bug倉庫 // 程式日記

    Jerry 發表在 痞客邦 留言(0) 人氣()