正在尝试获取非对象的属性[laravel 5.2]


Trying to get property of non-object [laravel 5.2]

项目5.2版

我是Laravel 5的新学员。plz解决

error:试图获取非对象的属性

Comment.php[model]

namespace App;
use Illuminate'Database'Eloquent'Model;
class Comment extends Model
{
    //
    public function articals()
    {
        return $this->belongsTo('App'Artical');
    }
    protected $fillable = array('body','artical_id');

}

Article.php[model]

namespace App;
use Illuminate'Database'Eloquent'Model;
class Artical extends Model
{
    //
    public function comments()
    {
        return $this->hasMany('App'Comment');
    }
    protected $fillable = array('title','body');

}

route.php[route]

 use App'Artical;
 use App'Comment;
Route::get('/', function ()
{
 $c = Artical::find(18)->comments;
  foreach($c as $comment) 
  {
    print_r($comment->body.'<br />'); 
  }
}); // working ok.....but
  $a = Comment::find(18)->articals;
  print_r($a->title); // error:Trying to get property of non-object 


}

获取错误:试图获取非对象的属性

plz帮我…

文章表结构

注释表结构

我认为你的关系可能不正常。从代码中猜测关系是多对多?如果是这样,那么这些关系应该属于ToMany。还要确保你正在定义关系,并且它在正确的模型上是相反的(取决于哪个有外键(。

https://laravel.com/docs/5.2/eloquent-relationships#defining-关系

问题在于Comment模型上的articles()关系。

如果您没有在belongsTo关系中指定外键,它会根据关系方法的名称构建外键名称。在这种情况下,由于您的关系方法是articles(),它将查找字段articles_id

您要么需要将articles()关系重命名为article()(这很有意义,因为只有一篇文章(,要么需要在关系定义中指定密钥名称。

class Comment extends Model
{
    // change the relationship name
    public function article()
    {
        return $this->belongsTo('App'Article');
    }
    // or, specify the key name
    public function articles()
    {
        return $this->belongsTo('App'Article', 'article_id');
    }
}

注意,这与关系的hasOne/hasMany侧不同。它基于类的名称构建密钥名称,因此无需更改comments()关系在Article模型上的定义方式。

更改以下行

$a = Comment::find(18)->articles;

$a = Comment::find(18);