Laravel Eloquent 的 BelongsToThrough 关系
BelongsToThrough 此种反向版本的 HasManyThrough 允许具有无限中间模型的 BelongsToThrough 关系。 支持 Laravel 5.0+。 安装 composer require staudenmeir/belongs-to-through:"^2.5" 如果您在 Windows 上使用 PowerShell (例如在 VS Code 中),请使用以下命令: composer require staudenmeir/belongs-to-through:"^^^^2.5" 版本 | Laravel | 包 | |:--------|:--------| | 13.x | 2.18 | | 12.x | 2.17 | | 11.x | 2.16 | | 10.x | 2.13 | | 9.x | 2.12 | | 8.x | 2.11 | | 7.x | 2.10 | | 6.x | 2.6 | | 5.x | 2.5 | 使用 - 自定义外键 - 自定义本地键 - 表别名 - 软删除 考虑以下 HasManyThrough 关系: Country → 具有多个 → User → 具有多个 → Post php 类 Country extends Model { public function posts() { return $this-hasManyThrough(Post::class, User::class); } } 在您的模型中使用 BelongsToThrough 特征来定义反向关系: Post → 归属于 → User → 归属于 → Country php 类 Post extends Model { use \Znck\Eloquent\Traits\BelongsToThrough; public function country(): \Znck\Eloquent\Relations\BelongsToThrough { return $this-belongsToThrough(Country::class, User::class); } } 您还可以定义更深层次的关系: Comment → 归属于 → Post → 归属于 → User → 归属于 → Country 以数组形式提供中间模型作为第二个参数,从相关模型(Country)到父模型(Comment): php 类 Comment extends Model { use \Znck\Eloquent\Traits\BelongsToThrough; public function country(): \Znck\Eloquent\Relations\BelongsToThrough { return $this-belongsToThrough(Country::class, [User::class, Post::class]); } } 自定义外键 您可以指定自定义外键作为第五个参数: php 类 Comment extends Model { use \Znck\Eloquent\Traits\BelongsToThrough; public function country(): \Znck\Eloquent\Relations\BelongsToThrough { return $this-belongsToThrough( Country::class, [User::class, Post::class], foreignKeyLookup: [User::class = 'customuserid'] ); } } 自定义本地键 您可以为关系指定自定义本地键: VendorCustomerAddress → 归属于 → VendorCustomer 在 VendorCustomerAddress.vendorcustomerid 中 VendorCustomerAddress → 归属于 → CustomerAd…
暂无开放 Issues,或尚未同步最近议题。