简体   繁体   English

Laravel Eloquent获取一个与数据透视表中的值匹配的关系

[英]Laravel Eloquent get a relation that matches a value in pivot table

I need to get model that must match with the value stored in a pivot table, but unfortunately i couldn't get the solution. 我需要获取必须与存储在数据透视表中的值匹配的模型,但是不幸的是我无法获得解决方案。

Here is my schema 这是我的图式

PEROPERTY TABLE
id


FILTER TABLE
id

FILTER_OPTION TABLE
id
filterId

FILTER_OPTION_TRANSLATE TABLE
optionId
languageId
title

PROPERTY_FILTER TABLE
propertyId
filterId
optionId

What i wanto to do is: 我想做的是:

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

but here the problem for me is how to say get option matches optionId in PROPERTY_FILTER TABLE 但在我这里的问题是如何说在PROPERTY_FILTER TABLE中获取选项与选项ID匹配

My models: 我的模特:

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);
}

I hope i can get some help, thanks from now. 我希望我能得到一些帮助,从现在开始。

I solved my problem by using pivot table as seperated model. 我通过使用数据透视表作为单独的模型解决了我的问题。

I was trying to get 3 level far relation through pivot table but even intermediate model couldn't solve my problem, and i just tried a seperated model. 我试图通过数据透视表获得3级远的关系,但即使是中间模型也无法解决我的问题,我只是尝试了一个单独的模型。

Firstly, i created Property_Filter model that represents property_filter pivot table and I added filter and option methods as below shown: 首先,我创建了表示property_filter数据透视表的Property_Filter模型,并添加了filter和option方法,如下所示:

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

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

Then converted filters relationship method 然后转换滤镜的关联方法

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

to

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

Now i reach the filter and option selected for iterated filter like below shown: 现在我到达过滤器,并为迭代过滤器选择了选项,如下所示:

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM