---
# System prepended metadata

title: Laravel Model Relation
tags: [laravel]

---

# Laravel Model Relation
###### tags: `laravel`

## hasOne 
> [官方文件](https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Concerns/HasRelationships.html#method_hasOne)

```php=
public function BuildCaseHouseHold(){
    // 
    return $this->hasOne(BuildCaseHouseHold::class, 'id', 'house_hold_id');
}
```

## hasMany
```php=
public function BuildCaseHouseHolds(){
    return $this->hasMany(BuildCaseHouseHold::class, 'build_case_id', 'id');
}
```

## hasOneThrough hasManyThrough
### hasOneThrough(目標類, 中繼類, 中繼類對目前類的外來鍵, 目標類對中繼類的外來鍵, 目前類對中繼類的關聯欄位, 中繼類對目標類的關聯欄位)

目標類 => target
中繼類 => relation
目前類 => current

hasOneThrough(target::class, relation::class, [relation->foreign key for current], [target->foreign key for relation], [current->key for relation], [relation->key for target])


