Laravel foreach在一个项目?

问题描述 投票:0回答:3

我有一种关系

+------------+---------+
|    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();
php laravel laravel-5 foreach
3个回答
0
投票
$problem=Problem::select()
            ->leftjoin('solution','problem.id','=','solution.problemid')
            ->where('solution.id',$id)
            ->get();

0
投票

您应该使用GROUP_CONCTAT函数

编辑:现在是正确的:D

DB::select('problem.*','solution.*')
        ->addSelect(DB::raw('GROUP_CONCAT(solution.solution)'))
        ->from('problem')
        ->join('solution', function($join) {
            $join->on('problem.id', '=', 'solution.problemid');
            })
        ->get();

0
投票

我找到了解决方案,我在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

© www.soinside.com 2019 - 2024. All rights reserved.