我对此感到困惑:我正在尝试以某种博客格式构建一些多语言支持。我有一些帖子(我称之为新闻)我需要两种语言。我现在拥有的是语言表和新表。
语言 - ID - 名称 - 代码
newss - ID - parent_id - lang_id - slu .. - 标题 - 身体
到目前为止一切正常。我可以将新闻保存到数据库中。唯一令人讨厌的问题是在索引新闻页面中我无法获得语言代码。 我有一个带有{{$ news-> language-> code}}的foreach循环,它检索“试图获取非对象的属性”。
我会与你分享我的模特,控制器和观点,希望有人可以为我所看到的错误带来一些启示。
型号:
Languages.php
<?php
class Language extends Eloquent {
protected $fillable = array('name', 'code');
public static $rules = array(
'name'=>'required|min:3',
'code'=>'required|min:2'
);
public function news() {
return $this->hasMany('News');
}
}
News.php
<?php
class News extends Eloquent {
protected $fillable = array('parent_id', 'lang_id', 'slug', 'title', 'body');
protected $table = 'newss';
public static $rules = array(
'parent_id'=>'integer',
'lang_id'=>'required|integer',
'title'=>'required|min:3'
);
public function language() {
return $this->belongsTo('Language');
}
public function parent_news() {
return $this->belongsTo('News','parent_id');
}
public function child_news() {
return $this->hasMany('News','parent_id');
}
}
控制器:
NewsController.php
public function index()
{
$newss = News::all();
$languages = array();
foreach(Language::all() as $language) {
$languages[$language->id] = $language->code;
}
return View::make('admin.news.index')
->with('newss', $newss)
->with('languages', $languages);
}
查看:
@foreach($newss as $news)
<tr class="gradeA">
<td>{{ $news->title}}</td>
<td>{{ $news->language->code}}</td>
<td>{{ HTML::linkRoute('admin.news.edit', '', array($news->id), array('class' => 'btn btn-warning btn-circle glyphicon glyphicon-pencil')) }}</td>
<td>{{ Form::open(['method' =>'DELETE', 'route'=>['admin.news.destroy', $news->id], 'class'=>'form-inline']) }}
{{ Form::hidden('id', $news->id) }}
{{ Form::button('<i class="fa fa-times"></i>', array('type' => 'submit', 'class' => 'btn btn-danger btn-circle')) }}
</td>
{{ Form::close() }}
</tr>
@endforeach
答案 0 :(得分:1)
public function language() {
return $this->belongsTo('Language','lang_id');
}