Laravel 5数据透视表不能工作


Laravel 5 pivot tables are not working

我正试图使用数据透视表关系从数据库更改主页文本语言。所有的工作都很好,我没有得到任何错误,但登录字不显示。我有3个表

的语言
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>
?>

如有任何帮助将不胜感激))

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

语言模型:

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

在你的索引视图中,你需要像下面这样访问数据:

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

由于数据透视表有额外的列text,因此在定义关系时需要定义列名

根据官方文件

默认情况下,只有模型键会出现在pivot对象上。如果数据透视表包含额外的属性,则必须在定义关系时指定它们:

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

对于检索中间表列,需要使用pivot属性。

语言模型

<?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>
?>