首页 文章

Laravel雄辩关系返回空数组

提问于
浏览
1

我想用“users”显示一个链接,一个页面,一个标签和许多带有用户名的注释,但是,注释返回一个空数组 . 所有表都有“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);
}   
}

型号(评论)

class Comment扩展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($链接);

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

CONTROLLER:$ link = Link :: where('friendly_url',$ id) - > with('page','tag','comments.user','comments.userProfile') - > first();

dd($link);

DD($链接)

#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
      ]

1 回答

  • 0

    1,数据库:您必须在评论表中包含 link_iduser_id

    2, Controller :您应该使用 with() 函数来获取 commentsuser

    $link = Link::with(['page', 'tag', 'comments' => function($query){
               $query->with('user')
        }])->where('friendly_url', $id)->first();
    
        return view('site.link', compact('link'));
    

    您可以使用 dd($link) 来检查关系数据

    你可以尝试一下 . 您可以在下方发表评论,以便为您提供支持

相关问题