2017-02-11 34 views
0

有一個能夠保存每個用戶感興趣的「類別」和/或「品牌」的ID的「興趣」。 爲了防止創建兩個單獨的表對於user_category_interestsuser_brand_interest我添加了一個名爲type的枚舉列。參考兩個表時的Laravel DB架構

現在我不知道如何在架構生成器中創建遷移,如何設置關係和外鍵......以利用使用Eloquent方法。

Schema::create('user_interests', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->enum('type', ['categories', 'brands']); 
     $table->integer('reference_id')->unsigned(); 
     $table->timestamps(); 
    }); 

有沒有更好的方法,而不是創建兩個單獨的表和模型?

P.S.我使用laravel 5.4

Brands Table: 
id | name 
----------- 
1 | Adidas 
2 | Nike 
3 | Puma 

Categories Table: 
id | name 
----------- 
1 | Clothes 
2 | Luxury 
3 | Sport Wear 


User_Interests Table: 
id | user_id | type | reference_id 
----------------------------------------- 
1 | 113  | 'brand' | 2 
1 | 113  | 'brand' | 3 
2 | 113  |'category'| 3 
3 | 224  | 'brand' | 1 
+0

[Laravel可能重複,我需要多個數據庫表在不同模型上的投票](http://stackoverflow.com/questions/29222441/laravel-do-i-need-multiple-database-tables-for-票據不同模型) – patricus

回答

1

是的 - read the docs on polymorphic relations

它的工作方式類似於您的所得,但您可能有名爲interestable_idinterestable_type的列(如果您願意,可以將其配置爲其他內容)。 interestable_type將從字面上看是引用類名稱的字符串表示形式,如App\BrandApp\Categoryinterestable_id將是該模型的主鍵。

最好的部分是它的全部通過洋洋灑灑做它已經好去與各協會,急切加載等

編輯:我要補充一點,你的3臺設立仍然表示這種結構的最佳方式,只是對您使用的列名提出建議,以及如何使用Eloquent將其掛鉤。

+0

該死!我昨晚沒有讀到的唯一部分是多態關係! – Hadu