【问题标题】:Query returns Object(Builder), undefined property查询返回 Object(Builder),未定义的属性
【发布时间】:2017-09-20 01:54:34
【问题描述】:

我有以下代码

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 正确添加)。现在,当我想显示带有车辆信息的详细信息页面时,就会出现这个问题,如上面的代码所示。 希望它足够清楚。感谢您的建议。

【问题讨论】:

  • 你的查询最后不需要-&gt;get()吗?

标签: sql postgresql laravel query-builder


【解决方案1】:

尝试在控制器中添加-&gt;get()-&gt;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

【讨论】:

  • 谢谢老兄,它有效!顺便说一句,我没有替换forelse,但我假设它只是以防万一没有车辆,对吗?以及为什么添加paginate 使其工作?我不明白。
  • @Ady96 是的。 forelse 可以过滤你的查询是否为空,兄弟。
  • @Ady96 您可以同时使用get() 之一,您将获得所有结果。和paginate 你可以分页你的结果。它使您的网站负载不重。
  • 我知道它的作用,但我不明白为什么没有paginateget 会出现该错误。
  • @Ady96 如果没有任何paginategetfirstlast。它只是一个查询生成器。不是你可以通过对象得到的结果。这就是原因。 xD
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多