php - 调用未定义的方法 Illuminate\Database\Eloquent\Relations\HasMany::withTimestamps()
问题描述
我正在尝试在 laravel 中创建带有时间戳的关系。我有这个应用程序,允许客户向市场请求工作。当市场上的自由职业者找到他们感兴趣的工作时,他们建议完成该工作,并在自由职业者表中查询新行。
这是创建关系的代码:
$marketplace->freelancers()->create([
'request_id' => $id,
'user_id' => $user->id
]);
这是市场模型关系代码:
/**
* A request may have multiple freelancers
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function freelancers()
{
return $this->hasMany('App\Models\MainFreelancers')->withTimestamps();
}
这是自由职业者模型关系代码:
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function mainMarketplace()
{
return $this->belongsTo('App\Models\MainMarketplace');
}
当尝试运行第一个代码块时,我不断收到这个 Laravel 错误:
BadMethodCallException
Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::withTimestamps()
在短期内,我只是手动添加了一个strtotime()
,但我更喜欢使用 Laravel 提供的功能。有人有建议吗?
注意我在这里引用了一个以前的stackoverflow问题: Timestamps are not updated while attaching data in pivot table 但不幸的是它没有帮助。
解决方案
withTimestamps();
用于多对多关系中,您要声明连接表中有 created_at 和 updated_at 列。
$withTimestamps 指示数据透视表上是否有可用的时间戳。
正如例外正确指出的那样,Illuminate\Database\Eloquent\Relations\HasMany
没有withTimestamps()
方法。
https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Relations/HasMany.html