【问题标题】:Select and display columns with hasMany relation Laravel选择并显示具有 hasMany 关系 Laravel 的列
【发布时间】:2017-08-17 10:26:05
【问题描述】:

我无法从具有hasManybelongsToMany 等关系的两个表中进行选择。

我有桌子items

id 
title

和表review

id
item_id

这是在我的项目模型中

public function review()
{
    return $this->hasMany('App\Review', 'item_id','id');
}

在我的评论模型中

public function item()
{
    return $this->belongsToMany('App\Item', 'item_id','id');
}

控制器

public function index()
{
    $reviews = Review::with('item')->get();
    return view('index', compact('reviews'));
}

在视图中,我想显示评论表中的所有 reviews 和项目表中的 titles

@foreach($reviews as $review)    
     {!!$review->item()->title!!}    
@endforeach

错误

SQLSTATE[42S02]:未找到基表或视图:1146 表“ps.item_id”不存在(SQL:选择items.*、item_id.idpivot_id、@987654337 @.item_id as pivot_item_id from items 内连接 item_id on items.id = item_id.item_id where item_id.@987654347,@ in (5,17, 18、19、20、21、22、23、24、25))

显然我的关系是错误的。有谁能帮帮我吗?

【问题讨论】:

  • 您在Review 模型中的belongsToMany 关系应该是belongsTo 关系。

标签: laravel laravel-5


【解决方案1】:

你们的关系设置有点不对。

您当前有一个hasMany 关系,其逆是belongsToMany,这是一个多对多关系。

这意味着每个项目都有多个评论(这是正确的)。
但这也意味着每条评论都适用于多个项目(我认为这是错误的)。

要解决此问题,您可以将 Review 中的 item() 函数替换为以下内容:

public function item()
{
    return $this->belongsTo('App\Item', 'item_id','id');
}

这会将您的关系更改为一对多关系。

每个项目仍然有多个评论,但现在每个评论只链接到一个项目。这也将允许您的其他代码(控制器)工作。

此外,您应该从视图中的调用中删除 perentesis。将其作为函数调用将返回关系而不是实际模型。

【讨论】:

  • 现在它运行良好。谢谢你的解释!将在 5 分钟内接受答复。
猜你喜欢
  • 2019-09-28
  • 2022-11-23
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多