简体   繁体   中英

Laravel eloquent relationship return empty array

I want to show one link, one page, one tag, and many comments with user name from "users", but, the comments return one empty array. All tables have "id" as primary key and auto increment.

Controller:

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

Model (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);
}   
}

Model (comments)

class Comment extends Model
{

    public function user(){
        return $this->belongsTo(User::class);
    }
    }

View:

    @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 ▶}
          ]
        }
      ]

SOLVED:

$link->getRelation('comments');

But I want to show the userProfile too, but return 0...

CONTROLLER:

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

1, Database: You must have link_id and user_id in the comments table

2, Controller : You should use with() function to get comments and user

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

    return view('site.link', compact('link'));

You can use dd($link) to check relationship data

You can try them. You can comment below for me to support you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM