我试图在我的文章中回显用户的名字,并且我得到了
ErrorException:尝试获取非对象的属性
我的密码:
模型
1. News
class News extends Model
{
public function postedBy()
{
return $this->belongsTo('App\User');
}
protected $table = 'news';
protected $fillable = ['newsContent', 'newsTitle', 'postedBy'];
}
2. User
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
}
模式
表users
表news
控制器
public function showArticle($slug)
{
$article = News::where('slug', $slug)->firstOrFail();
return view('article', compact('article'));
}
叶片
{{ $article->postedBy->name }}
当我试图删除刀片{{ $article->postedBy }}
中的名称时,它会输出id
,但是当我尝试在那里添加->name时,它会显示Trying to get property of non-object but I have a field
名称in my table and a
User`‘model。我是不是遗漏了什么?
发布于 2015-09-09 01:47:35
您的查询是否返回数组或对象?如果将其转储出去,您可能会发现它是一个数组,您所需要的只是一个数组访问([]),而不是对象访问(->)。
发布于 2015-09-09 01:56:34
我通过使用吉米·佐托应答并向belongsTo
添加第二个参数来使其工作。下面是:
首先,正如Jimmy所建议的,我在刀片中的代码来自
$article->poster->name
至
$article->poster['name']
接下来,在我的belongsTo
中添加第二个参数,
return $this->belongsTo('App\User');
至
return $this->belongsTo('App\User', 'user_id');
其中user_id
是我在新闻表中的外键。
发布于 2019-07-27 16:28:15
如果您使用或循环(for
、foreach
等)或者关系(one to many
、many to many
等),这可能意味着其中一个查询正在返回null
变量或null
关系成员。
(例如,):在表中,您可能希望将users
与其roles
一起列出。
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->role->name }}</td>
</tr>
@endforeach
</table>
在上面的例子中,,如果有一个用户没有角色,您可能会收到这个错误。您应该将{{ $user->role->name }}
替换为{{ !empty($user->role) ? $user->role->name:'' }}
,如下所示:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ !empty($user->role) ? $user->role->name:'' }}</td>
</tr>
@endforeach
</table>
编辑:您可以使用Laravel的optional
方法来避免错误(更多信息)。例如:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ optional($user->role)->name }}</td>
</tr>
@endforeach
</table>
如果您使用的是PHP8,则可以使用null safe operator
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user?->name }}</td>
<td>{{ $user?->role?->name }}</td>
</tr>
@endforeach
</table>
https://stackoverflow.com/questions/32469542
复制相似问题