【问题标题】:Laravel - Trying to get property of non-objectLaravel - 试图获取非对象的属性
【发布时间】:2014-06-23 09:10:02
【问题描述】:

我对此感到困惑:我正在尝试以某种博客格式构建多语言支持。我有一些需要两种语言的帖子(我称之为新闻)。我现在拥有的是一个语言表和一个新闻表。

语言 - ID - 姓名 - 代码

新闻 - ID - parent_id - lang_id - 蛞蝓 - 标题 - 身体

到目前为止一切正常。我能够将新闻保存到数据库中。唯一烦人的问题是在索引新闻页面中我无法获得语言代码。 我有一个带有 {{ $news->language->code}} 的 foreach 循环,它检索“尝试获取非对象的属性”。

我将与您分享我的模型、控制器和视图,希望有人能够为我所看到的错误带来一些启示。

型号:

语言.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

【问题讨论】:

    标签: php laravel models multilingual


    【解决方案1】:
    public function language() {
        return $this->belongsTo('Language','lang_id');
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-22
      • 2017-03-20
      • 2014-03-25
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多