【发布时间】:2018-06-19 22:18:44
【问题描述】:
我想显示一个链接、一个页面、一个标签和许多带有来自“users”的用户名的 cmets,但是 cmets 返回一个空数组。所有表都有“id”作为主键并自动递增。
控制器:
$link = Link::with('page', 'tag', 'comments.user')->where('friendly_url', $id)->first();
return view('site.link', compact('link'));
模型(链接)
class Link extends Model
{
public function page()
{
return $this->belongsTo(Page::class);
}
public function tag()
{
return $this->belongsTo(Tag::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
模型(cmets)
class Comment extends Model
{
public function user(){
return $this->belongsTo(User::class);
}
}
查看:
@foreach($link->comments as $comment)
<li class="comment">
<h1>{{ $comment->user->name . $comment->user->lastname }}</h1>
<h2>{{ $comment->content }}</h2>
@endforeach
dd($link);
0 => Link {#291 ▼
#relations: array:3 [▼
"page" => Page {#295 ▶}
"tag" => Tag {#289 ▶}
"comments" => Collection {#292 ▼
#items: array:2 [▼
0 => Comment {#299 ▶}
1 => Comment {#301 ▶}
]
}
]
已解决:
$link->getRelation('comments');
但我也想显示 userProfile,但返回 0...
控制器:
$link = Link::where('friendly_url', $id)->with('page', 'tag', 'comments.user', 'comments.userProfile')->first();
dd($link);
#relations: array:3 [▼
"page" => Page {#296 ▶}
"tag" => Tag {#290 ▶}
"comments" => Collection {#293 ▼
#items: array:2 [▼
0 => Comment {#300 ▶}
1 => Comment {#302 ▼
#relations: array:2 [▼
"user" => User {#305 ▶}
"userProfile" => null
]
【问题讨论】:
-
comments表中有link_id和user_id吗?你试过Link::with('page', 'tag', 'comments', 'comments.user')吗? -
您的
->where子句中的$id到底是什么? -
是的,表格有两个字段... $id = 'cars-more-expensive-in-2017'(友好的网址)...是的,我也尝试过这种方式...
-
我在DD中编辑了结果,看那里,获得了cmets...
-
0 => 链接 {#291 ▼ #relations: array:3 [▼ "page" => 页面 {#295 ▶} "tag" => 标签 {#289 ▶} "cmets" = > 收藏 {#292 ▼ #items: array:2 [▼ 0 => 评论 {#299 ▶} 1 => 评论 {#301 ▶} ] } ]