2017-02-21 78 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开始)。如果您感到困惑,请仔细观察一下。