2014-05-06 64 views
0

我對此感到困惑:我試圖以某種博客格式構建一些多語言支持。我有兩個語言需要的帖子(我稱之爲新聞)。我現在所擁有的是一個語言表和一個新表。Laravel - 嘗試獲取非對象的屬性

語言 - ID - 姓名 - 代碼

newss - ID - PARENT_ID - LANG_ID - 塞 - 標題 - 身體

一切工作正常,直到如今。我可以將新聞保存到數據庫。唯一惱人的問題是,在索引新聞頁面我無法獲得語言代碼。 我有一個foreach循環{{$ news-> language-> code}},它檢索「嘗試獲取非對象的屬性」。

我會與你分享我的模型,控制器和視圖,希望有人能爲我所看到的錯誤帶來一些亮點。

型號:

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 

回答

1
public function language() { 
    return $this->belongsTo('Language','lang_id'); 
} 
+0

謝謝剃鬚刀,它現在是明顯的... –

相關問題