如何使用Eloquent获得多个结果

时间:2018-04-28 10:42:14

标签: laravel-5

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

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();

错误显示

方法Illuminate \ Database \ Eloquent \ Collection :: getData不存在

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

我的版本是5.6

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 [▶]
}

刀片文件

 @if (isset($record))
    <table>
    <tr><th>result</th></tr>
    <tr>
       <td>{{$record->getResult()}}</td>
    </tr>
    </table>
</div>
    @endif

这是Class

class st extends Model
{

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

1 个答案:

答案 0 :(得分:0)

使用$record时,

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

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