2017-08-13 82 views
0

我需要獲取必須與存儲在數據透視表中的值匹配的模型,但不幸的是我無法獲得解決方案。Laravel Eloquent獲得與數據透視表中的值匹配的關係

這裏是我的架構

PEROPERTY TABLE 
id 


FILTER TABLE 
id 

FILTER_OPTION TABLE 
id 
filterId 

FILTER_OPTION_TRANSLATE TABLE 
optionId 
languageId 
title 

PROPERTY_FILTER TABLE 
propertyId 
filterId 
optionId 

我wanto做的是:

@foreach($property->filters as $filter) 
    {{ $filter->option->translate->title }} 
@endforeach 

但在這裏,對我來說,問題是怎麼說的獲取選項中PROPERTY_FILTER表匹配optionId

我的型號:

PROPERTY MODEL 
public function filters() 
{ 
    return $this->belongsToMany(Filter::class, 'PROPERTY_FILTER','propertyId','filterId'); 
} 

FILTER MODEL 
public function option() 
{ 
    return $this->hasMany(Filter_Option::class, 'filterId'); 
} 

FILTER OPTION MODEL 
public function translate() 
{ 
    return $this 
    ->hasOne(Filter_Option_Translate::class, 'optionId') 
    ->where('langId', currentLanguage()->langId); 
} 

我希望我能得到一些幫助,從現在開始感謝。

回答

0

我解決了我的問題,使用數據透視表作爲分離模型。

我試圖通過數據透視表得到3級遠的關係,但即使是中級模型也解決不了我的問題,我只是嘗試了一個分離的模型。

首先,我創建表示property_filter透視表Property_Filter模型和我添加過濾器和選擇方法,如下所示:

public function filter() 
{ 
    return $this->belongsTo(Filter::class, 'filterId'); 
} 

public function option() 
{ 
    return $this->belongsTo(Filter_Option::class, 'filterValue'); 
} 

然後轉換濾波器關係方法

public function filters() 
{ 
    return $this->belongsToMany(Filter::class, 'PROPERTY_FILTER','propertyId','filterId'); 
} 

public function filters() 
{ 
    return $this->hasMany(Property_Filter::class,'propertyId'); 
} 

現在我到達過濾器和選項迭代fil ter如下所示:

@foreach($properties as $property) 
    @foreach($property->filters as $filter) // here i get filters chosen for iterated property 
    <span class="caption">{{ $filter->filter->translate->entryTitle }}</span> // here i get iterated filters title (translated) 
    <span class="value">{{ $filter->option->translate->entryTitle }}</span> // here i get chosen option for iterated filter not all options belognsto iterated filter 
    @endforeach 
@endforeach 
相關問題