>和latestOfMany()
的方法,用于有效检索关系中最新或最古老的相关模型。 这简化了否则需要复杂排序和过滤的查询。oldestOfMany()
>
考虑一个方案跟踪用户登录和购买:
这是一个更全面的示例,用于管理客户互动,购买和订阅:
class User extends Model { public function lastLogin(): HasOne { return $this->hasOne(Login::class)->latestOfMany(); } public function firstPurchase(): HasOne { return $this->hasOne(Purchase::class)->oldestOfMany(); } }
访问此数据很简单:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasOne; class Customer extends Model { public function lastInteraction(): HasOne { return $this->hasOne(Interaction::class)->latestOfMany(); } public function largestPurchase(): HasOne { return $this->hasOne(Purchase::class)->ofMany('total_amount', 'max'); } public function initialSubscription(): HasOne { return $this->hasOne(Subscription::class)->oldestOfMany('started_at'); } public function activeMembership(): HasOne { return $this->hasOne(Membership::class)->latestOfMany()->where('status', 'active'); } }
>
和// Retrieve customers with related data $customers = Customer::with([ 'lastInteraction', 'largestPurchase', 'initialSubscription', 'activeMembership' ])->get(); // Access relationship attributes foreach ($customers as $customer) { echo "Last Contact: " . $customer->lastInteraction->created_at . PHP_EOL; echo "Largest Purchase: $" . $customer->largestPurchase->total_amount . PHP_EOL; }
以上是Laravel中的最新和最古老的关系方法的详细内容。更多信息请关注PHP中文网其他相关文章!