[英]Property [file] does not exist on this collection instance Laravel
I have three tables('users,cars and photos').我有三张桌子('用户、汽车和照片')。
users table用户表
photos table照片表
I want to display the newest image file for user avatar picture.我想显示用户头像图片的最新图像文件。 In this case I want to show as profile avatar photo with id = 2 because it's the latest photo for the user(id=1) because of imageable_id=1 and because imageable_type is for User(for user avatar).
在这种情况下,我想显示为 id = 2 的个人资料头像照片,因为它是用户 (id=1) 的最新照片,因为 imageable_id=1 并且因为 imageable_type 用于用户(用于用户头像)。 App\Models\Car belongs to cars and I don't need that for now.
App\Models\Car 属于汽车,我现在不需要它。
Summary: Want to display the newest photo for the user avatar.摘要:想为用户头像显示最新的照片。
I Am using this code below inside my blade file:我在刀片文件中使用以下代码:
<img src="{{$detected_user->photo->file}}" alt="">
In Controller I use $detected_user to authenticate user which is logged in and I use '->photo'(relationship inside my model).在控制器中,我使用 $detected_user 对登录的用户进行身份验证,并使用'-> photo'(模型内部的关系)。 '->file' is the name of the column inside my 'photos' table.
'->file' 是我的 'photos' 表中列的名称。
User Model用户模型
public function photo() {
return $this->morphMany('App\Models\Photo', 'imageable');
}
Cars Model汽车模型
public function photo() {
return $this->morphMany('App\Models\Photo', 'imageable');
}
Photo Model照片模型
public function imageable() {
return $this->morphTo();
}
On the User
model you can define two relationships在
User
模型上,您可以定义两个关系
//App\Models\User.php
public function photos()
{
return $this->morphMany('App\Models\Photo', 'imageable');
}
public function latest_photo()
{
return $this->morphOne('App\Models\Photo', 'imageable')->latest('id');
}
In the view在视图中
<img src="{{$detected_user->latest_photo->file}}" alt="">
And similarly for the Car
model同样对于
Car
模型
//App\Models\Car.php
public function photos()
{
return $this->morphMany('App\Models\Photo', 'imageable');
}
public function latest_photo()
{
return $this->morphOne('App\Models\Photo', 'imageable')->latest('id');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.