【发布时间】:2016-12-23 10:25:09
【问题描述】:
项目版本 5.2
我是 Laravel 5 的新手。请解决...
错误r:试图获取非对象的属性
Comment.php [型号]
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 [型号]
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 [路由]
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
}
得到错误:试图获取非对象的属性
请帮帮我...
【问题讨论】:
-
显示错误的哪一行?
-
它告诉你什么文件会引发错误?
-
表示
$a不是对象,也就是说articles大概为null。Article::comments()应该是hasMany(Comment::class)和Comment::articles()应该是Comment::article()。修复关系可能意味着为评论返回一篇文章,这意味着$a->title将起作用 -
检查
Comment::find(18)是否存在 -
$a = Comment::fint(18); print_r($a); // 输出 Empty Not ANY GETTING ERROR but $a = Comment::fint(18)->articles; // 得到错误:试图获取非对象的属性