gpt4 book ai didi

A Laravel 8 Accessor is Undefined for database table with pivot (with its own timestamps too) table, for JSON response to React Front end(对于具有PIVOT(也有自己的时间戳)表的数据库表,未定义Laravel 8访问器,以便JSON响应反应前端)

转载 作者:bug小助手 更新时间:2023-10-28 13:14:39 25 4
gpt4 key购买 nike



I am encountering an issue on Laravel, an exception is thrown because of an "undefined" created_at column on one of the database tables (but not the pivot table). The accessor in question is returning a human friendly format for the date. The data is sent to the client as JSON. Here are the tables:

我在Laravel上遇到了一个问题,由于其中一个数据库表(但不是透视表)上的一个“未定义的”Created_at列引发了异常。正在讨论的访问者正在返回日期的人类友好格式。数据以JSON的形式发送到客户端。以下是各表:


class Link extends Model
{
use HasFactory;

protected $primaryKey='id';
protected $table='links';
protected $perPage=24;

protected $appends = [
'human_friendly',
'slug',
];

protected $fillable = [
'url',
'active',
'slug',
'title',
'site_name',
'twitter_site',
'description',
'locale'
];

protected $hidden = [];

protected $casts = [
'active' => 'boolean',
];

public function getSlugAttribute()
{
return Str::slug($this->attributes['slug']);
}

public function getHumanFriendlyAttribute()
{
// problem arises from here
return Carbon::parse($this->attributes['created_at'])->diffForHumans();
}

public function users()
{
return $this->belongsToMany(User::class);
}
}

class User extends Authenticatable implements JWTSubject
{
use HasApiTokens, HasFactory, Notifiable;

protected $primaryKey='id';
protected $table='users';
protected $perPage=24;

protected $appends = [];

protected $fillable = [
'username',
'active',
'email',
'password',
'slug',
];

protected $hidden = [
'password',
'remember_token',
];

protected $casts = [
'email_verified_at' => 'datetime',
'active'=>'boolean',
];

public function getJWTIdentifier()
{
return $this->getKey();
}

public function getJWTCustomClaims()
{
return [];
}

public function links()
{
return $this->belongsToMany(Link::class);
}
}

The pivot table also has timestamp columns (the migration schema):

数据透视表还具有时间戳列(迁移方案):


Schema::create('link_user', function (Blueprint $table) {
$table->bigInteger('link_id')->unsigned()->index();
$table->bigInteger('user_id')->unsigned()->index();
$table->primary(['link_id', 'user_id']);
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();

$table->foreign('link_id')->references('id')->on('links')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

As you can see there is nothing out of the ordinary although I do suspect it's because the pivot table also have the timestamp columns. Has anyone else ran into this problem and shed some light on this problem?

正如您所看到的,没有什么异常,尽管我确实怀疑这是因为数据透视表也有时间戳列。有没有其他人遇到过这个问题,并对这个问题做出了一些解释?


Aside from this, the JSON is received very well. Thanks in advance.

除此之外,JSON也很受欢迎。先谢谢你。


更多回答
优秀答案推荐

The issue you're encountering is related to the created_at column not being available on the links table, but it's being accessed in the getHumanFriendlyAttribute accessor of your Link model. The problem doesn't seem to be directly related to the pivot table's timestamps.

您遇到的问题与Links表中不可用的Created_at列有关,但它可以在您的Link模型的getHumanFriendlyAttribute访问器中访问。这个问题似乎与数据透视表的时间戳没有直接关系。


To resolve this issue, you have a few options:

要解决此问题,您有以下几种选择:



  1. Ensure created_at Column Exists:
    The most straightforward solution is to make sure that the created_at column exists in your links table. If it's not present and you want to use it in your accessor, you should create it in the table schema.


Schema::create('links', function (Blueprint $table) {
#This line adds created_at and updated_at columns
$table->timestamps();
});

If you don't intend to use these columns, you can omit the $table->timestamps() line, and Laravel won't expect them.

如果您不打算使用这些列,您可以省略$table->Timestamp()行,Laravel不会想到它们。



  1. Customize Accessor:
    If you don't want to add the created_at column to your links table, you can modify the getHumanFriendlyAttribute accessor to handle cases where the column might not exist. You can check if the column exists in the $attributes array before using it:


public function getHumanFriendlyAttribute(){
if (array_key_exists('created_at', $this->attributes)) {
return Carbon::parse($this->attributes['created_at'])->diffForHumans();
} else {
return 'N/A';// or any default value
}
}

This way, if the created_at column is missing, it will return a default value or handle it as you see fit.

这样,如果CREATED_AT列丢失,它将返回一个缺省值或按您认为合适的方式处理。



  1. Remove created_at Accessor:
    If you don't actually need the created_at attribute in your JSON response, you can remove the getHumanFriendlyAttribute accessor altogether if it's not essential for your application.


Choose the option that best fits your requirements, whether it's adding the created_at column, customizing the accessor, or removing it based on your specific needs.

选择最符合您需求的选项,无论是添加Created_at列、定制访问器,还是根据您的特定需求删除它。


更多回答

The created_at column does exist in the database (from the schema migrated), which is more irritable for me why it is undefined. I don't per se need the column in the JSON response, only the mutated form of the timestamp. But I will update the class method to prevent the exception breaking things. Any other thoughts would be welcome :)

数据库中确实存在Created_at列(来自迁移的模式),这对我来说更令人恼火的是它为什么是未定义的。我本身并不需要JSON响应中的列,只需要时间戳的变异形式。但我会更新类方法以防止异常破坏。欢迎任何其他想法:)

how about using $this->created_at instead of $this->attributes['created_at'] ?

使用$This->Created_at代替$This->属性[‘Created_at’]怎么样?

The issue has since been resolved thank you :)

该问题已得到解决,谢谢:)

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com