【问题标题】:Laravel foreach in one item?Laravel foreach 在一项中?
【发布时间】:2018-03-04 16:31:25
【问题描述】:

我有这样的关系

+------------+---------+
|    id      | problem |
+------------+---------+
| 1          | problem |    
+------------+---------+


+------------+----------+---------+
|    id      | problemid|solution |
+------------+----------+---------+
| 1          |  1       |solution1|    
+------------+----------+---------+
| 2          |  1       |solution2| 
+------------+----------+---------+

我已经完成了连接,问题是当我在视图中执行 foreach 时,我得到 2 个具有相同问题的项目和 2 个不同的解决方案,但我需要得到相同的问题(一个问题)和 2 个解决方案。我该怎么做?

这是Controller中的代码:

$problem=Problem::select()
            ->join('solution','problem.id','=','solution.problemid')
            ->where('problem.id',$id)
            ->get();

【问题讨论】:

  • 使用relationships 更优雅地做到这一点
  • @JiFus 我已经这样做了,但是我还有另一个问题,那就是我正在使用 join。
  • 如果您的主要兴趣点是问题,以及相关的解决方案,我认为您应该在“problem.id”而不是“solution.id”的地方做。但显然,如果您只有一条记录有问题,那将没有什么区别。
  • 当您在 where 条件下使用 solution.id 时,您如何获得两种不同的解决方案对您的问题的回答将在 where 条件下使用 problem.id
  • @mwal 我的错误,在我的查询中我有问题。我编辑它。

标签: php laravel laravel-5 foreach


【解决方案1】:
$problem=Problem::select()
            ->leftjoin('solution','problem.id','=','solution.problemid')
            ->where('solution.id',$id)
            ->get();

【讨论】:

  • OP 为什么要试试这个好的答案将始终解释所做的事情以及这样做的原因,不仅适用于 OP,而且适用于可能会发现此问题并正在阅读您的答案的 SO 的未来访问者。跨度>
  • 我仍然得到同样的东西,我有一个集合和 2 个项目,但我需要一个项目,因为我有相同的问题名称,当我做一个 foreach 时,我得到([问题 1 解决方案 1] ,[problem1, solution2]) 但我需要 ([problem1, solution1,solution2])
【解决方案2】:

我找到了解决方案并在 View 中使用:

@foreach ($problem as $probl)
    @if ($loop->first)
        Here i put the code for fist item
    @endif

@endforeach

对于正在搜索相同问题的其他人来说,这里是文档:

https://laravel.com/docs/5.3/blade#the-loop-variable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 2014-10-04
    • 2017-05-15
    • 1970-01-01
    相关资源
    最近更新 更多