【发布时间】:2021-06-20 10:04:37
【问题描述】:
我正在通过以下方式从控制器中检索数据:
public function show($id)
{
$news = News::select('id','heading', 'body', 'image','category')->with('newsCategory')->where('id', $id)->first();
return view('pages.news_details')->with('news', $news);
}
新闻模型是
public function newsCategory()
{
return $this->belongsTo(Category::class, 'category');
}
我得到了成功的回应
{"id":1,"heading":"Fugiat veniam nons.",
"body":"lorem ipsum dolor sit amet",
"image":null,
"category":4,
"news_category":{"id":4,"title":"health care","created_at":null,"updated_at":null}}
但是,我试图在刀片文件中访问它。除news-category 外,所有属性均可访问。这是我尝试访问它的方式
$news->news_category->title
dd($news->toArray())返回
但它不起作用。我怎样才能以这种方式访问该属性?
【问题讨论】:
-
关系是
newsCategory而不是news_category。 -
dd($news->toArray());在返回视图并将其发布到问题之前
-
添加了@JohnLobo
-
试试 $news->newsCategory ->title
-
哦..!那行得通。但是一个问题是 dd 中的
news_category但为什么newsCategory有效?