zing / laravel-eloquent-relationships
为Laravel提供更多优雅的关系
2.2.1
2024-09-12 02:21 UTC
Requires
- php: ^8.0
- illuminate/database: ^8.69 || ^9.0 || ^10.0 || ^11.0
- illuminate/support: ^8.69 || ^9.0 || ^10.0 || ^11.0
Requires (Dev)
- mockery/mockery: ~1.3.3 || ^1.4.2
- nunomaduro/larastan: ^1.0 || ^2.0
- orchestra/testbench: ^6.0 || ^7.0 || ^8.0 || ^9.0
- phpunit/phpunit: ^9.3.3 || ^10.0 || ^11.0
- zing/coding-standard: ^6.4 || ^7.0
README
需求
使用Composer安装Laravel Eloquent Relationships
composer require zing/laravel-eloquent-relationships
用法
BelongsToOne
BelongsToOne
基于BelongsToMany
差异
- 返回相关模型而不是模型集合
- 如果关系不存在,则返回
null
而不是空模型集合 - 支持在关系不存在的情况下返回默认相关模型
示例
<?php use Illuminate\Database\Eloquent\Model; use Zing\LaravelEloquentRelationships\HasMoreRelationships; use Zing\LaravelEloquentRelationships\Relations\BelongsToOne; use Zing\LaravelEloquentRelationships\Tests\Models\User; class Group extends Model { use HasMoreRelationships; public function leader(): BelongsToOne { return $this->belongsToOne(User::class) ->wherePivot('status', 1) ->withDefault(function (User $user, self $group): void { $user->name = 'leader for ' . $group->name; }); } }
MorphToOne
MorphToOne
基于MorphToMany
差异
- 返回相关模型而不是模型集合
- 如果关系不存在,则返回
null
而不是空模型集合 - 支持在关系不存在的情况下返回默认相关模型
示例
<?php use Illuminate\Database\Eloquent\Model; use Zing\LaravelEloquentRelationships\HasMoreRelationships; use Zing\LaravelEloquentRelationships\Relations\MorphToOne; use Zing\LaravelEloquentRelationships\Tests\Models\Product; class Image extends Model { use HasMoreRelationships; public function bestProduct(): MorphToOne { return $this->morphedByOne(Product::class, 'imageable', 'model_has_images'); } }
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Zing\LaravelEloquentRelationships\HasMoreRelationships; use Zing\LaravelEloquentRelationships\Relations\MorphToOne; use Zing\LaravelEloquentRelationships\Tests\Models\Image; class Product extends Model { use HasMoreRelationships; public function cover(): MorphToOne { return $this->morphToOne(Image::class, 'imageable', 'model_has_images')->withDefault([ 'url' => 'https://example.com/default.png', ]); } }
许可
Laravel Eloquent Relationships是一个开源软件,许可协议为MIT许可。