Laravel雄辩关系返回空数组

时间:2018-01-10 17:06:09

标签: laravel eloquent

我想用“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 ...

控制器:     $ link = Link :: where('friendly_url',$ id) - &gt; with('page','tag','comments.user','comments.userProfile') - &gt; 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 :(得分: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)检查关系数据

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