【问题标题】:Laravel | Why is the id missing in a eloquent model?拉拉维尔 |为什么雄辩的模型中缺少 id?
【发布时间】:2021-06-02 20:45:02
【问题描述】:

我们是customizing our key 在我们的路由中使用唯一标识符。

所以这个

http://127.0.0.1:8000/TEAMS/1

这样结束

http://127.0.0.1:8000/TEAMS/91e11f44-2d89-4b5e-83e0-5cb92d0c0ebd

这很好用,但不幸的是,我们在另一个地方遇到了错误。 创建新团队时,我们无法访问该新团队的id

您会看到primaryKey 指向id-属性,但attributes-数组中缺少该属性。所以我们无法访问

$newTeam->id 
// or
$newTeam['id']

目前我们正在使用创建后获取团队

$team = Team::where('identifier', $newTeam->identifier)->first();

但这似乎是多余的。

有人知道如何解决这个问题吗?提前致谢。

编辑

这是来自model的相关部分

class Team extends JetstreamTeam
{
    use \App\Http\Traits\UsesIdentifier;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'identifier',
        'name',
        'personal_team',
    ];


    /**
     * Specify the routing key
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'identifier';
    }
}

迁移:

class CreateTeamsTable extends Migration
{
    public function up()
    {
        Schema::create('teams', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->index();
            $table->string('name');
            $table->boolean('personal_team');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('teams');
    }
}

性状:

trait UsesIdentifier
{
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->identifier = (string) Str::uuid();
        });
    }

    public function getIncrementing()
    {
        return false;
    }

    public function getKeyType()
    {
        return 'string';
    }
}

【问题讨论】:

  • 你能在这里展示你的模型和迁移吗?
  • 是我遗漏了什么还是您的数据库中没有identifier 列?它在迁移中丢失了
  • 你的权利..但它在我们的数据库中,所以它必须被错误地删除。我会检查一下,谢谢。

标签: php laravel eloquent jetstream


【解决方案1】:

由于您的表的主键信息不足,我可以假设如下。

  • 您提到您正在使用自定义主键。标识符列。因此,您的表中没有 id 列。默认的find() 方法适用于id 字段。

  • 要使其与您自定义的identifier 列一起使用,您必须如下定义主键。

class User extends Model
{
    protected $primaryKey = 'identifier';
}

在此之后,您可以像这样访问模型:

$team = Team::find($newTeam->identifier);

【讨论】:

  • 感谢您的回复。我编辑我的问题。我们仍然使用 id 作为主键来识别我们的条目。标识符只是用于路由的附加组件。
  • \App\Http\Traits\UsesIdentifier 这个是干什么用的?
  • 我认为id 被添加到基类或特征内某处的隐藏属性中。
  • 对不起,我忘了提,请看我的编辑。
  • 我删除了“getIncrementing”功能,它似乎可以工作。非常感谢!!你能解释为什么'getIncrementing'会导致这个问题吗?我不明白..
猜你喜欢
  • 1970-01-01
  • 2017-09-02
  • 2015-08-24
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
  • 2021-08-23
相关资源
最近更新 更多