我有3个表,用户表,图像表和收藏夹表有点像数据透视表,因为它只有ID,image_id和user_id。
在我的用户模型中,我有:
$result = $s3->putObject(array(
'Bucket' => $this->bucket,
'SourceFile' => $temp,
'Key' => $Destination_folder,
'ACL' => 'public-read',
'ContentType' => 'text/plain',
'Expires' => $expire
));
在我最喜欢的控制器中,我有:
public function FavoritedByMe() {
return $this->hasMany('CommendMe\Models\Favorite', 'user_id');
}
如果我想获取我最喜欢的所有图片的ID,这样就可以了。
public function getFavorites($username) {
$user = User::where('username', $username)->first();
return view('user.favorites')
->with('user', $user);
}
然而,我真的希望能够用图像本身返回视图。类似的东西:
@foreach ($user->FavoritedByMe as $favorite)
{{ $favorite->image_id }}
@endforeach
现在显然这不会起作用,并会返回错误:
FavoritesController.php第54行中的ErrorException:未定义的属性:Illuminate \ Database \ Eloquent \ Collection :: $ image_id
但也许某种雄辩的关系呢?我尝试过这些工作,但他们只是没有点击"在我脑海里。
我怎样才能做到这一点?
提前致谢!
答案 0 :(得分:1)
在Favorite
模型中添加此关系:
public function image()
{
return $this->belongsTo('YourImageModel');
}
然后你可以像这样访问图像:
@foreach ($user->FavoritedImages as $favorite)
{{ $favorite->image->yourProperty }}
@endforeach
在laravel的最佳做法中,您应该调用FavoritedByMe
关系favorites
,因为它显然与用户有关。