我的应用程序的结构如下: Property与Manager具有多对多关系,而Unit与Property具有一对多关系,即,一个经理可以管理多个属性,一个属性可以具有多个经理帐户,而一个属性可以有多个单位.
My application is structured as follows: Property has a Many-Many relationship with Manager, and a Unit has a One-Many relationship with a Property, i.e. A manager can manage multiple properties, one property can have multiple manager accounts and one property can have multiple units.
我想在经理上拥有一个HasManyThrough关系来获取他的所有单位,因此理想情况下,它看起来像是:$manager->units而不是通过循环遍历每个属性并在其上调用$property->units.当前版本的laravel是否有可能?
I would like to have a HasManyThrough relationship on the manager to get all his units, so ideally it would look something like: $manager->units instead of having through loop through each property and call $property->units on it. Is this possible with the current version of laravel?
经理:
- id
属性:
- id
managers_properties:
managers_properties:
- manager_id
- property_id
单位:
- id
- property_id
除了hasManyThrough之外,口才版目前没有链式关系方法,该方法仅适用于2个链式hasMany关系.您应该创建自己的实现以获取相关资源.最简单的方法是在型号:
Eloquent currently does not have methods for chained relations, other than the hasManyThrough, that is only applicable to 2 chained hasMany relations. You should create your own implementation to fetch the related resources. The simplest way is to define an accessor on the Manager model:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Support\Collection; /** * @property-read Collection|\App\Models\Property[] $properties * @property-read Collection|\App\Models\Unit[] $units */ class Manager extends Model { public function properties(): BelongsToMany { return $this->belongsToMany(Property::class); } public function getUnitsAttribute(): Collection { return $this->properties ->pluck('units') ->flatten(1) ->unique('id') ->sortBy('id'); } }您现在应该能够使用$manager instanceof App\Models\Manager访问$manager->units来访问相关单元.
You should now be able to access the related units with $manager->units assuming $manager instanceof App\Models\Manager.
注意
调用$manager->units 做最多执行n + 1数据库查询:1用于获取n相关属性,另一个n用于为每个返回的属性获取相关单元.之所以最多",是因为先前对访问器的调用可能已经加载了资源.
Calling $manager->units does perform at most n + 1 database queries: 1 for fetching n related properties, and another n for fetching related units for each returned property. "At most" because the resources might have been loaded already because of previous calls to the accessor.
注意
调用$manager->units会返回Unit模型的Collection,该格式等效于您从一对多关系方法的魔术访问器中获得的格式.但是getUnitsAttribute()不是 实际的关系方法(它不返回关系对象),因此不能如此对待,而Manager::properties()可以这样.
Calling $manager->units returns you a Collection of Unit models, a format that's equivalent to what you'd get from the magic accessor of a to-many relationship method. However getUnitsAttribute() is not an actual relationship method (it does not return a relationship object), so it can not be treated as such, whereas Manager::properties() can be.
更多推荐
hasManyThrough和一个中间数据透视表
发布评论