2016-08-16 43 views
2

我正在尝试使用数据透视表关系从数据库更改主页文本语言。 所有工作正常,我没有得到任何错误,但登录词不显示。 我有3个表Laravel 5数据透视表不起作用

语言

id | name | sign | default_back 
1 | English | en  | 1 
2 | Russian | ru  | 0 

功能

id | code | type  
70 | login | 0 

feature_language

id | feature_id | language_id | text 
1 | 70   | 2   | Ru Login 
2 | 70   | 1   | Login 

语言模型

<?php // Languages Model 
namespace App; 
use Illuminate\Database\Eloquent\Model; 
class Language extends Model 
{ 
    public function features(){ 
      return $this->belongsToMany('App\Feature'); 
    } 
    public function getDefaulLanguage(){ 
     return $this->default_back; 
    } 
    public function featureTranslation($code){ 
     return $this->features()->where('code', '=', $code)->first(); 
    } 
} 
?> 

功能特点型号

<?php // Features Model 
namespace App; 
use Illuminate\Database\Eloquent\Model; 
class Feature extends Model 
{ 
} 
?> 

指数控制器

<?php // index controller 
namespace App\Http\Controllers 
use App\Language; 
class HomeController extends Controller { 

    public function index(){ 
     $languages = Language::get(); 
     $language_default = Language::where('default_back', '>', '0')->first(); 

     return view('index')->with('languages', $languages) 
          ->with('language_default', $language_default); 
    } 
} 
?> 

索引视图

<?php 
<h1>login : {{ $language_default->featureTranslation("login")->text}}</h1> 
?> 

任何帮助将不胜感激))

+0

我做了它使用本机mysql –

+0

请解释更多 –

+0

我使用DB :: select(DB :: raw(“SQL QUERY”))来使用本地SQL查询来转换它 –

回答

1

首先,您需要在模型中定义数据透视表列的名称。

语言模型:

public function features() 
{ 
    return $this->belongsToMany('App\Feature')->withPivot('text'); 
} 

在你索引视图,您需要访问数据,如下列:

{{ $language_default->featureTranslation("login")->pivot->text }} 
+0

非常感谢:)作品 –

0

由于您的数据透视表中有额外的列text,你需要 来定义列名,同时限定的关系

根据Official Doc

缺省情况下,只有在模型键将存在于枢轴对象上。如果您的数据透视表中包含额外的属性,你必须定义的关系时指定它们:

public function features(){ 
    return $this->belongsToMany('App\Feature')->withPivot('text'); 
} 

以及用于获取中间表列,您需要使用pivot属性。

+0

试过,但我得到一个错误说:“基表或视图未找到:1146表'cmslaravel.text'不存在” –

+0

糟糕!我想我错过了与关系中的'withPivot'。 – jonju

0

语言模型

<?php // Languages Model 
namespace App; 
use Illuminate\Database\Eloquent\Model; 
class Language extends Model 
{ 
    public function features(){ 
      return $this->belongsToMany('App\Feature', 'feature_language', 'feature_id', 'language_id')->withPivot('text'); 
    } 
    public function getDefaulLanguage(){ 
     return $this->default_back; 
    } 
    public function featureTranslation($code){ 
     return $this->features()->where('code', $code)->first()->pivot->text; 
    } 
} 
?> 

索引视图

<?php 
<h1>login : {{ $language_default->featureTranslation("login") }}</h1> 
?>