2017-08-13 104 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 
相关问题