【发布时间】:2021-05-23 15:34:19
【问题描述】:
我有一个包含许多联系人的客户模型。我想创建一个分页和按最新联系人排序的联系人视图/列表。
客户.php
public function contacts()
{
return $this->hasMany(Contact::class);
}
public function latestContact()
{
return $this->hasOne(Contact::class)->latestOfMany()->withDefault();
}
在视图中,我想向客户展示这样的:
@foreach ($customers as $customer)
<x-table.row wire:key="row-{{ $customer->id }}">
<x-table.cell>
{{ $customer->last_name }}, {{ $customer->first_name }}
</x-table.cell>
<x-table.cell>
{{ $customer->latestContact->contacted_at }}
</x-table.cell>
</x-table.row>
@endforeach
表结构
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->string('first_name');
$table->string('last_name');
});
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->foreignId('customer_id');
$table->string('type');
$table->string('body');
$table->timestamp('contacted_at');
});
我正在努力为此获得正确的查询。这是我的最后一次尝试,它给了我以下错误:
照亮\数据库\查询异常 SQLSTATE[42S22]:未找到列:1054 未知列 'latestContact.contacted_at' in 'order Clause'...
return view('livewire.dashboard', [
'customers' => Customer::with('customers.*', 'latestContact.contacted_at')
->join('contacts', 'contacts.customer_id', '=', 'customers.id')
->orderBy('latestContact.contacted_at')
->paginate(25)
]);
感谢您的支持!
【问题讨论】:
-
为什么不直接使用属性?
-
@ChamaraAbeysekara 你到底是什么意思?能详细点吗?
-
使用
$append并有一个getLatestContactAttribute()函数返回$this->contacts->latest() -
我认为这不能解决我的问题。我能够附加属性。但是,我仍然无法对结果进行排序和分页。要么我使用
orderBy()->paginate()找不到附加的列,要么我使用get()->sortBy()->paginate()也不起作用,因为 Collection 实例无法分页。有什么想法吗?