我的模型如下:
常问问题:
class Faq extends Model
{
use Translatable;
public $translatedAttributes = ['question', 'answer'];
public function faqtranslations()
{
return $this->hasMany(FaqTranslation::class);
}
}
和常见问题翻译:
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
)数组的其他成员也是如此。
我在这里想念什么?
最佳答案
以这种方式重构代码。
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');
希望能帮助到你 :)
关于mysql - 在MySQL,Laravel和Translation中的某些列中获取null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44462726/