【问题标题】:Getting data in a table with matching IDs to the pivot table in Laravel在 Laravel 中获取具有匹配 ID 的表中的数据到数据透视表
【发布时间】:2016-12-09 11:26:35
【问题描述】:

我有 3 个表,用户表、图像表和收藏夹表,它们的工作方式有点像数据透视表,因为它只有 ID、image_id 和 user_id。

在我的用户模型中,我有:

public function FavoritedByMe() {
    return $this->hasMany('CommendMe\Models\Favorite', 'user_id');
}   

在我的收藏夹控制器中,我有:

public function getFavorites($username)  {
    $user = User::where('username', $username)->first();    

    return view('user.favorites')
        ->with('user', $user);
}   

如果我想获取我收藏的所有图像的 ID,这很好用:

@foreach ($user->FavoritedByMe as $favorite)
  {{ $favorite->image_id }}
@endforeach

但是,我真正希望能够返回带有图像本身的视图。比如:

$favImages = Images::where('id', $user->FavoritedByMe->image_id);

return view('user.favorites')
       ->with('user', $user)
       ->with('favImages', $favImages);

现在显然这不起作用,并且会返回错误:

FavoritesController.php 第 54 行中的 ErrorException:未定义属性:Illuminate\Database\Eloquent\Collection::$image_id

但也许某种雄辩的关系会?我已经尝试过让这些工作,但他们只是没有在我的脑海中“点击”。

我怎样才能做到这一点?

提前致谢!

【问题讨论】:

  • 您有我们可以处理的错误吗?
  • 已编辑以显示假设代码将显示的错误。

标签: php mysql laravel


【解决方案1】:

在您的 Favorite 模型中添加此关系:

public function image()
{
   return $this->belongsTo('YourImageModel');
}

然后你可以像这样访问图像:

@foreach ($user->FavoritedImages as $favorite)
  {{ $favorite->image->yourProperty }}
@endforeach

在 laravel 的最佳实践中,您应该将 FavoritedByMe 关系称为 favorites,因为它显然与用户相关。

【讨论】:

  • 在尝试您给我的内容时,我收到错误“尝试获取非对象的属性”。我会更新我的帖子以展示我的尝试。
猜你喜欢
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 2017-05-17
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
相关资源
最近更新 更多