拉拉维尔 |为什么在 eloquent 模型中缺少 id?

时间:2021-03-04 08:16:49

标签: php laravel eloquent jetstream

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

所以这个

http://127.0.0.1:8000/TEAMS/1

就这样结束

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

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

dd

您看到 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';
    }
}

1 个答案:

答案 0 :(得分:1)

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

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

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

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

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

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