Php Laravel |为什么雄辩的模型中缺少id?
我们将在路由中使用唯一标识符 那么这个Php Laravel |为什么雄辩的模型中缺少id?,php,laravel,eloquent,jetstream,Php,Laravel,Eloquent,Jetstream,我们将在路由中使用唯一标识符 那么这个 http://127.0.0.1:8000/TEAMS/1 就这样结束了 http://127.0.0.1:8000/TEAMS/91e11f44-2d89-4b5e-83e0-5cb92d0c0ebd 这很有效,但不幸的是,我们在另一点上遇到了错误。 创建新团队时,我们无法访问新创建团队的id: 您可以看到,primaryKey指向id-属性,但是属性-数组中缺少该属性。所以我们无法访问 $newTeam->id // or $newTea
http://127.0.0.1:8000/TEAMS/1
就这样结束了
http://127.0.0.1:8000/TEAMS/91e11f44-2d89-4b5e-83e0-5cb92d0c0ebd
这很有效,但不幸的是,我们在另一点上遇到了错误。
创建新团队时,我们无法访问新创建团队的id
:
您可以看到,primaryKey
指向id
-属性,但是属性
-数组中缺少该属性。所以我们无法访问
$newTeam->id
// or
$newTeam['id']
目前,我们正在获取创建后的团队
$team = Team::where('identifier', $newTeam->identifier)->first();
但这似乎是多余的
有人知道如何解决这个问题吗?提前感谢。
编辑
这是模型的相关部分
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';
}
}
由于没有足够的关于表主键的信息,我可以假设如下
- 您已经提到您正在使用自定义主键。标识符列。因此,表中没有
列。默认的id
方法适用于find()
字段id
- 要使其与自定义的
标识符
列一起工作,必须按如下所示定义主键
$team = Team::find($newTeam->identifier);
您能在这里显示您的模型和迁移吗?我是否遗漏了什么,或者您的数据库中没有
标识符列?它在你右边的Migiration中丢失了。。但是它在我们的数据库中,所以它必须被错误地删除。我查一下,谢谢。谢谢你的回复。我编辑我的问题。我们仍然使用id作为主键来标识条目。标识符只是用于路由的附加组件。它用于\App\Http\Traits\UsesIdentifier
?我认为id
添加到基类或trait中的隐藏属性中。哦,很抱歉,我忘了提及,请查看我的编辑。我删除了“getIncrementing”函数,它似乎可以工作。谢谢!!你能解释一下为什么“getIncrementing”会出现这个问题吗?我不明白。。
$team = Team::find($newTeam->identifier);