【问题标题】:In Laravel - Add a variable to a model, without putting it in the database在 Laravel 中 - 将变量添加到模型中,而不将其放入数据库中
【发布时间】:2020-01-23 08:20:54
【问题描述】:

我有一个已在多个地方使用的团队模型,它从 API 端点中的数据库返回字段。

目前访问并返回如下:

$team = Team::find(1)
return $team;

我想向返回的集合添加一个计算变量。我想我可以将它添加到模型的构造函数中,从而将它与当前使用团队模型的所有地方一起获取,如下所示:

class Team extends Model
{

    protected $table = 'teams';
    protected $fillable = [
        'id',
        'created_at',
        'updated_at',
        'team_name'
    ];

    public $number_of_players;

    public function __construct( array $attributes = [] ){
        $this->number_of_players = 3; //This number should be calculated
        parent::__construct( $attributes );
    }
}

但这不起作用。 如何将变量添加到获取团队模型的所有位置?

我还研究了API Resources。我看起来这可能是一个解决方案,但我发现它非常冗长和长发解决方案(另外,我也无法让它工作)。

【问题讨论】:

  • 如何在模型上使用自定义方法来返回您的计算结果。这样你就可以在任何你想要的地方使用模型上的方法。
  • 你为什么不用助手?
  • @guttume - 如果我添加一个自定义方法,那么我是否需要在访问团队模型的任何地方调用Team::with( 'number_of_players')->find( 1 )?这是我想避免的整个“必须通过所有地方的模型被调用”。
  • @RiponUddin - 我该怎么做?
  • @Zeth 您可以在模型上设置with 属性以在每个请求上进行预加载。 ` /** * 每个查询都急切加载的关系。 * * @var 数组 */ 受保护的 $with = []; `

标签: laravel


【解决方案1】:

你可以使用访问器/修改器

假设你们有关系

团队->玩家(团队有很多玩家)

你可以这样做

在团队模型中

class Model extends Model {
    public function players()
    {
        return $this->hasMany(Player::class, 'team_id', 'id');
    }
}

现在你可以做到了

<?php
class Model extends Model {
    protected $appends = ['number_of_players'];

    public function players()
    {
        return $this->hasMany(Player::class, 'team_id', 'id');
    }

    public function getNumberOfPlayersAttribute()
    {
        return $this->players->count();
    }
}

然后访问像App/Team::find(1)-&gt;number_of_players这样的球队的球员人数

【讨论】:

    猜你喜欢
    • 2013-08-15
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 2017-06-23
    • 1970-01-01
    相关资源
    最近更新 更多