簡體   English   中英

Laravel Eloquent獲取一個與數據透視表中的值匹配的關系

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

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

這是我的圖式

PEROPERTY TABLE
id


FILTER TABLE
id

FILTER_OPTION TABLE
id
filterId

FILTER_OPTION_TRANSLATE TABLE
optionId
languageId
title

PROPERTY_FILTER TABLE
propertyId
filterId
optionId

我想做的是:

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

但在我這里的問題是如何說在PROPERTY_FILTER TABLE中獲取選項與選項ID匹配

我的模特:

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

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

我通過使用數據透視表作為單獨的模型解決了我的問題。

我試圖通過數據透視表獲得3級遠的關系,但即使是中間模型也無法解決我的問題,我只是嘗試了一個單獨的模型。

首先,我創建了表示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');
}

然后轉換濾鏡的關聯方法

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

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

現在我到達過濾器,並為迭代過濾器選擇了選項,如下所示:

@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