【发布时间】:2019-10-03 18:14:55
【问题描述】:
我正在编写一个小程序,我想根据当前用户 customer_id 显示所有位置。 在这种逻辑中,客户是公司向我们购买的产品,因此客户与用户不同。客户可以有多个位置,我想根据当前用户的 customer_id 显示位置。
为此,我编写了以下代码: 这是引发错误的代码。
if (isset(auth()->user()->customer_id) && !auth()->user()->hasRole('admin')) {
$customer = Customer::find(auth()->user()->customer_id);
$locations = $customer->locations()->get();
} else {
$locations = Location::all();
}
return view('locations.index', ['locations' => $locations]);
我检查用户是否有 customer_id 并且不是管理员。 如果两者都是真的,我会让客户连接到 customer_id。 然后我检索与该客户相关的所有位置。 这一切都有效,当我用 dd($var) 检查它时,它总是返回预期值。
index.blade.php
<table id="locations" class="table align-items-center table-flush" style="100%">
<thead class="thead-light">
<tr>
<th scope="col">{{ __('Customer') }}</th>
<th scope="col">{{ __('Location Name') }}</th>
<th scope="col">{{ __('Address') }}</th>
<th scope="col">{{ __('Postal Code') }}</th>
<th scope="col">{{ __('City') }}</th>
<th scope="col">{{ __('Country') }}</th>
</tr>
</thead>
<tbody>
@foreach ($locations as $location)
<tr>
<td>{{ $location->customer->name}}</td>
<td>{{ $location->name}}</td>
<td>{{ $location->address}}</td>
<td>{{ $location->postalcode}}</td>
<td>{{ $location->city}}</td>
<td>{{ $location->country}}</td>
</tr>
@endforeach
</tbody>
</table>
现在,当我返回视图时,我收到以下错误:
Method Illuminate\Database\Eloquent\Collection::links does not exist
这里奇怪的是,我已经以相同的方式返回了其他实体的数据,而且效果很好。 这段代码做同样的事情并且确实有效。
if (isset(auth()->user()->distributor_id) && !auth()->user()->hasRole('admin')) {
$distributor = Distributor::find(auth()->user()->distributor_id);
$customer = $distributor->customers()->get();
} else {
$customer = Customer::all();
}
return view('customers.index', ['customers' => $customer]);
在互联网上环顾四周后,我发现了这个问题:
Laravel 4 Call to undefined method Illuminate\Database\Eloquent\Collection::links()。 这个问题看起来很像我的问题,但遮阳篷并没有解决我的问题。我试图实现他们的 awnser,但我仍然遇到同样的异常。
谁能解释我为什么会收到这个错误?
【问题讨论】:
-
你用这个变量来分页吗?
-
也添加您的刀片文件。你在那里使用
links,这导致了问题 -
不,我只是将变量返回到视图并循环显示数据。就像我说的,在第二个代码块中它工作正常。
-
@Collin 在您的
$locations数组中是否有可用的links元素? -
@AmitSenjaliya 不,没有任何可用的链接元素