简体   繁体   English

Laravel-如何访问相关对象的其他冲突

[英]Laravel - How to access related object other relashionship

I have 3 Models "Category", "Post", and "User". 我有3个模型“ Category”,“ Post”和“ User”。 A Category has a hasMany relationship with Post. 类别与Post具有hasMany关系。 And a Post has a belongsTo relationship with User. 帖子与用户之间具有belongsTo关系。

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) 我有一个Category对象$cat1 ,我可以在其视图中访问其帖子(和user_id),但无法访问更多的用户数据(行名)

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

This throws an error 这引发一个错误

Undefined property: Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::$name 未定义的属性: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. 当您调用该函数时,它就是查询关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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