[英]Count number of elements via Laravel relationship
有不同類型的板,類型可以有多個板,板有多個用戶。
任務:獲取特定類型登機的用戶數量。
登機型號:
class BoardingType extends Model
{
public function boardings()
{
return $this->hasMany(Boarding::class, 'type');
}
}
登機型號:
class Boarding extends Model
{
public function users()
{
return $this->hasMany(User::class, 'boarding');
}
}
如何簡明扼要地獲取所有用戶的登機類型?
以類似的形式制作,我不喜歡實現:
foreach ($types as $type) {
$usersCount = 0;
foreach ($type->boardings as $boarding) {
$usersCount += $boarding->users()->count();
}
}
您可以在這里使用has-many-through關系。
在您的BoardingType
模型中
public function users()
{
return $this->hasManyThrough(User::class, Bording::class);
}
請注意,如果您的模型不遵循 laravel 密鑰約定,您可能必須指定 fk :
public function users()
{
return $this->hasManyThrough(
User::class,
Bording::class,
'bording_type_id', // Foreign key on the boarding table...
'boarding_id', // Foreign key on the users table...
'id', // Local key on the bording type table...
'id' // Local key on the boarding table...
);
}
您可以像這樣計算邊界類型的用戶數量:
$usersCount = $bordingType->users()->count();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.