2017-02-21 74 views
1

我正在分類網站上工作,我將有不同類型的廣告。將有汽車,房地產等。所有類型都將具有類型特定的屬性。例如,房地產廣告將具有汽車不需要的平方米屬性。Laravel 5種不同的廣告類型

我爲這種情況創建了數據庫模型,但不知道如何將這種關係說出來。還有沒有更好的方法來解決這個問題?

廣告表 -id -date -ad_type_id

汽車表 -id -title -horse_power

房地產表 -id -title -squares

回答

1

什麼你正在尋找被稱爲「多態關係」。

如果您遵循https://laravel.com/docs/5.4/eloquent-relationships#polymorphic-relations的例子,只是與他們像這樣的東西取代你的表...

cars 
    id - integer 
    title - string 
    horse_power - integer 

realestates 
    id - integer 
    title - string 
    squares - integer 

ads 
    id - integer 
    description - text 
    adable_id - integer 
    adable_type - string 

You'l可以做你想做的。所以你只需要做

$ads = Ad::with('adable')->get() 

然後,這將是所有廣告(汽車和房地產)的集合。那麼你想創建3個葉片,像

ad_list.blade.php 
ad_car.blade.php 
ad_realestate.blade.php 

在你ads_list視圖,你會碰到這樣的

@foreach ($ads as $ad) 
    @include('ad_'.snakecase(classbasename($ad->adable_type))) 
@endforeach 

然後ad_carad_realestate格式要如何內容

//car view 
$ad->adable->title 
$ad->adable->horse_power 

這是一個奇怪的概念,它花了我幾個嘗試才把它做對。我發現https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/10有助於解釋在不同視圖中展示多態關係的概念(從8:30開始)。如果您感到困惑,請仔細觀察一下。