简体   繁体   中英

Laravel - How to access related object other relashionship

I have 3 Models "Category", "Post", and "User". A Category has a hasMany relationship with Post. And a Post has a belongsTo relationship with User.

I have a Category object $cat1 and i can access its posts (and the user_id) in my view, but i can't access more user data (line name)

@foreach ($cat1->posts as $post)
    {{ $post->title }}
    {{ $post->user()->name }}
@endforeach

This throws an error

Undefined property: Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::$name

You can access it like this:

{{ $post->user->name }}

When you call the function, it's to query the relationship.

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