【发布时间】:2022-01-21 23:23:27
【问题描述】:
我有一个有很多联系人的客户模型。我使用 Laravel 8 中的“Has One Of Many”关系定义了一个关系以获取客户的最新联系:
模型
class Customer extends Model
{
use HasFactory;
public function contacts()
{
return $this->hasMany(Contact::class);
}
public function latestContact()
{
return $this->hasOne(Contact::class)->ofMany('contacted_at', 'max')->withDefault();
}
}
class Contact extends Model
{
use HasFactory;
protected $casts = [
'contacted_at' => 'datetime',
];
public function customer()
{
return $this->belongsTo(Customer::class);
}
}
迁移(联系模型)
class CreateContactsTable extends Migration
{
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->softDeletes();
$table->foreignID('customer_id');
$table->string('type');
$table->dateTime('contacted_at');
});
}
}
在我看来,我想显示所有客户并按他们的最新联系人订购他们。但是,我不知道该怎么做。
我尝试通过 join 方法来实现它,但显然每个客户都有不同的条目。
$query = Customer::select('customers.*', 'contacts.contacted_at as contacted_at')
->join('contacts', 'customers.id', '=', 'contacts.customer_id')
->orderby('contacts.contacted_at')
->with('latestContact')
了解 Laravel 一定是实现这一目标的好方法或帮手。有什么想法吗?
【问题讨论】:
-
你的数据库中有时间戳吗?
-
是的,我愿意。但就我而言,“contacted_at”列是获取最新联系人的重要列。更新了我的帖子以正确反映它。
-
@maxiw46 你能发布你的完整模型吗?
-
那么你的目标是什么?显示按最新联系人排序的所有联系人?或者您只想显示几个最近的联系人?
-
你为什么不那样做?
Custumer::with('contacts')->get()->orderBy('contacted_at');在可以订购 cotacts 时,定义最新联系人的新方法的原因是什么?