2017-04-23 82 views
2

我有下面的代码查询返回对象(生成器),未定义的属性

public function detailCustomer(Customer $customer) 
    { 
     $vehicles = DB::table('vehicles') 
        ->selectRaw('*') 
        ->where('cust_id', '=', $customer->id); 
     return view('customers.detail', array('customer' => $customer, 'vehicles' => $vehicles)); 
    } 

凡表vehicles包括:

spz 
cust_id <FK> //this is foreign key to customer->id 
type 
brand 

customers.detail视图,我试着用下面的代码来显示数据,但我得到这个错误:

Undefined property: Illuminate\Database\PostgresConnection::$spz

代码:

@if (count($vehicles) > 0) 
    <?php $i = 1; ?> 

    @foreach ($vehicles as $vehicle) 
    <?php $i++; ?> 
    <td>{{$vehicle->spz}}</td> 
    <td>{{$vehicle->type}}</td> 
    <td>{{$vehicle->brand}}</td> 
    @endforeach 
@endif 

我已阅读this topic,但似乎这不是我的问题,因为我用foreach通过对象迭代,但似乎不知从数据库中获取对象变成我$vehicles变量,因为在错误页面,这也说明是这样的:

'customer' => object(Customer), 'vehicles' => object(Builder) 

什么让我觉得customer正确地得到它的对象,但vehicles得到Builder?真的不知道那里有什么问题。有任何想法吗? 只是为了描述我在做什么工作,我有一个客户详细信息页面,我点击一个按钮将车辆添加到他的详细信息页面(配置文件页面),并将客户id作为参数发送到功能我将车辆添加到数据库中,该数据库有效(车辆与客户id正确添加)。现在,当我想显示详细信息页面时,如上面的代码所示,车辆信息显示出现问题。 希望它清楚。感谢您的建议。

+4

请问您的查询不需要' - >获得()'就结束? – Joe

回答

1

尝试添加->get()->paginate($YOUR_LIMIT_ONE_PAGE)在控制器

public function detailCustomer(Customer $customer) 
{ 
    $vehicles = DB::table('vehicles') 
       ->selectRaw('*') 
       ->where('cust_id', '=', $customer->id)->get(); 
       // ->where('cust_id', '=', $customer->id)->paginate($YOUR_LIMIT_ONE_PAGE); 
    return view('customers.detail', array('customer' => $customer, 'vehicles' => $vehicles)); 
} 

并尝试更换您的foreach这个forelse

@forelse ($vehicles as $index => $vehicle) 
    <tr> 
     <td>{{$index}}</td> 
     <td>{{($vehicle->spz !== null) ? $vehicle->spz : '-'}}</td> 
     <td>{{($vehicle->type !== null) ? $vehicle->type : '-'}}</td> 
     <td>{{($vehicle->brand !== null) ? $vehicle->brand : '-'}}</td> 
    </tr> 
@empty 
    <td colspan='4'>Data not found</td> 
@endforelse 
+0

谢谢你,它的作品!顺便说一句,我没有取代'forelse',但我假设它只是在没有车辆的情况下,对吗?为什么添加'paginate'使其工作?我不明白。 – Ady96

+0

@ Ady96是的。 'forelse'可以过滤你的查询是否为空,bro。 –

+0

@Ady96你可以使用'get()'中的一个,你将得到所有的结果。和'paginate'你可以分页你的结果。这是让你的网站不重负荷。 –