【问题标题】:Laravel Nova show computed field in BelongsToMany sub tableLaravel Nova 在 BelongsToMany 子表中显示计算字段
【发布时间】:2019-10-23 19:33:36
【问题描述】:

使用 Laravel Nova,我想在 BelongsToMany 子视图中显示一个计算字段。在中间模型中,我设置了一个虚拟属性字段,它使用连接表计算一个值。但是,此字段未显示可能是因为 Nova 检查了 withPivot 字段(无法将其添加到该字段,因为它不是真实字段)。有没有其他方法可以让它工作?

这背后的数据库模型是:

[GameVariation] has BelongsToMany using [GameVariationMatch] with [GameMatch]

[GameMatch] HasOne [Match]

在 GameVariation 资源中,我设置了一个应该显示计算字段的 BelongsToMany 字段:

BelongsToMany::make( 'Game Matches', 'game_matches', GameMatch::class )
    ->fields( function () {
        return [
            Text::make( 'Match Data' )->displayUsing(function() {
                return $this->match_data;
            })
        ];
    } ),

在 GameVariation 模型中,表格与 BelongsToMany 相连:

final public function game_matches(): BelongsToMany {
    return $this->belongsToMany(
        GameMatch::class
    )
    ->using( GameVariationMatch::class );
}

在数据透视表模型 GameVariationMatch 中,计算字段的设置如下:

final public function getMatchDataAttribute(): string {
    return $this
        ->game_match
        ->match
        ->match_data;
}

【问题讨论】:

    标签: laravel-nova


    【解决方案1】:

    事实证明,在 GameVariation 资源上,从 GameMatch 资源提供 BelongsToMany 到 GameMatch 的索引视图。仅在 GameVariation BelongsToMany 字段上设置 ->fields() 时,它不会显示。推荐的方法是设置 ->fields() 使用这样的字段类:

    <?php
    
    
    namespace App\Nova\Fields;
    
    
    use App\Models\GameVariationMatch;
    use Illuminate\Http\Request;
    use Laravel\Nova\Fields\Text;
    
    class GameVariationMatchFields {
    
        /**
         * Get the pivot fields for the relationship.
         *
         * @param Request $request
         *
         * @return array
         */
        final public function __invoke( Request $request ): array {
            return [
                Text::make( 'Match Data', function ( GameVariationMatch $GameVariationMatch ) {
                    return $GameVariationMatch->match_data;
                } ),
            ];
        }
    }
    

    在上面,计算的文本字段接收中间枢轴模型,因此可以访问所有计算的属性。

    该字段类在 GameVariation 资源中用作:

    BelongsToMany::make( 'Game Matches', 'game_matches', GameMatch::class )
        ->fields( new RoundMatchVariationFields ),
    

    在 GameMatch 资源中为:

    BelongsToMany::make( 'Game Variations', 'game_variations', GameVariation::class )
        ->fields( new GameVariationMatchFields ),
    

    正如 Nova 官方文档中关于枢轴字段的描述 https://nova.laravel.com/docs/2.0/resources/relationships.html#belongstomany

    【讨论】:

    • 什么,字段的第一个参数可以是枢轴本身吗?谢谢!
    猜你喜欢
    • 2020-02-28
    • 2019-04-12
    • 2019-03-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 2019-12-30
    相关资源
    最近更新 更多