为MySQL,Laravel,Translation

时间:2017-06-09 16:31:46

标签: mysql laravel

我的模型如下:

常见问题:

class Faq extends Model
{
    use Translatable;

    public $translatedAttributes = ['question', 'answer'];

    public function faqtranslations()
    {
        return $this->hasMany(FaqTranslation::class);
    }
}

和FaqTranslation:

class FaqTranslation extends Model
{
    public $timestamps = false;

    protected $fillable = ['question', 'answer'];
}

这是来自FaqController的show方法:

public function show($id)
{
    $faq = Faq::find($id);

    $faq_translations = Faq::join('faq_translations as t', 't.faq_id', '=', 'faqs.id')
        ->where('t.faq_id', $id)
        ->select('t.locale','t.question','t.answer')
        ->get();

    return view('dashboard.faqs.show', compact('faq_translations'));
}

以下是视图页面上的结果:

  • {{$faq_translations}}正确显示[{"locale":"lv","question":"lv-q","answer":"lv-a"},{"locale":"ru","question":"ru-q","answer":"ru-a"},{"locale":"en","question":"en-q","answer":"en-a"}]
  • {{$faq_translations[0]->locale}}正确显示lv
  • {{$faq_translations[0]->question}}错误地显示null(应显示lv-q

对于阵列的其他成员也是如此。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

以这种方式重构您的代码。

public function show(Faq $faq)
{
    $faq_translations = $faq->faqtranslations()->get();

    return view('dashboard.faqs.show', compact('faq_translations'));
}

确保您在路线和控制器中具有相同的wildcard名称,即faq

Route::get('faqs/{faq}', 'FaqsController@show');

希望有所帮助:)