查询 returns 对象(生成器),未定义 属性

Query returns Object(Builder), undefined property

我有以下代码

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

其中 table 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

我已阅读 但似乎这不是我的问题,因为我使用 foreach 遍历对象但似乎我没有将对象从数据库获取到我的 $vehicles 变量中,因为在错误页面中,它还显示了这样的内容:

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

是什么让我认为 customer 正确获取其对象,但 vehicles 获取 Builder?真的不知道那里出了什么问题。有任何想法吗? 只是为了描述我在我从事的项目中所做的事情,我有一个客户详细信息页面,我在其中单击一个按钮将车辆添加到他的详细信息页面(个人资料页面),然后将客户 id 作为参数发送到我将车辆添加到数据库中的功能有效(车辆与客户一起正确添加 id)。现在,当我想显示带有车辆信息的详细信息页面(如上面的代码所示)时,问题就出现了。 希望它足够清楚。感谢您的建议。

尝试在您的控制器中添加 ->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