关于laravel 5:如何使用Eloquent获得多个结果

How to get multiple result using Eloquent

我可以使用此代码获得第一个结果

1
2
3
4
5
6
7
public function search(Request $request)
{
    $record = St::where('pn', $request->input)->first();
    $param = ['input' => $request->input, 'record' =>$record];
    return view('contacts.find', $param);

}

但是,我这样改变了

$ record = St :: where('pn',$ request-> input)-> get();

错误显示

方法照亮\\\\ Database \\\\ Eloquent \\\\ Collection :: getData不存在

有人可以告诉我为什么吗?

我的版本是5.6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
store {#717 ▼
  #connection:"mysql"
  #table: null
  #primaryKey:"id"
  #keyType:"int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:20 [?]
  #original: array:20 [?]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [?]
}

刀片文件

1
2
3
4
5
6
7
8
9
 @if (isset($record))
    <table>
    <tr><th>result</th></tr>
    <tr>
       <td>{{$record->getResult()}}</td>
    </tr>
    </table>

    @endif

这是Class

1
2
3
4
5
6
7
8
class st extends Model
{

    public function getResult()
    {
        return $this->pn;
    }
}


$record是使用get()时的集合。因此,您必须使用循环来访问单个实例。您还应该将其重命名为$records

1
2
3
4
5
6
7
8
9
10
11
public function search(Request $request)
{
    $records = St::where('pn', $request->input)->get();
    $param = ['input' => $request->input, 'records' => $records];
    return view('contacts.find', $param);
}


@foreach($records as $record)
   {{ $record->getResult() }}
@endforeach