调用未定义的方法Illuminate \ Database \ Eloquent \ Relations \ HasMany :: withTimestamps()

时间:2018-11-03 20:28:54

标签: php laravel eloquent

我正在尝试在laravel中创建带有时间戳的关系。我有这个应用程序,可让客户向市场请求工作。当市场上的自由职业者找到他们感兴趣的工作时,他们建议完成工作,并在自由职业者表中查询新行。

以下是创建关系的代码:

<form action="" id="myform">
  <input type="text" id="myinput" />
  <br/>
  <textarea id="mytext" cols="30" rows="10"></textarea>
  <input type="submit" id='submit' />
</form>

这是Marketplace模型的关联代码:

$marketplace->freelancers()->create([
   'request_id' => $id,
   'user_id' => $user->id
]);

这是Freelancer模型的关系代码:

    /**
     * A request may have multiple freelancers
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function freelancers()
    {
        return $this->hasMany('App\Models\MainFreelancers')->withTimestamps();
    }

当尝试运行第一个代码块时,我不断收到此Laravel错误: /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function mainMarketplace() { return $this->belongsTo('App\Models\MainMarketplace'); }

短期内,我只是手动添加了BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::withTimestamps(),但我更喜欢利用Laravel提供的功能。有人有建议吗?

注意,我在这里参考了以前的stackoverflow问题: Timestamps are not updating while attaching data in pivot table 但不幸的是,它没有帮助。

2 个答案:

答案 0 :(得分:0)

withTimestamps();用于多对多关系,您需要在其中声明连接表中有created_at和updated_at列。

  

$ withTimestamps指示数据透视表上是否有时间戳。

正如例外情况所正确指出的那样,Illuminate\Database\Eloquent\Relations\HasMany没有withTimestamps()方法。

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Relations/HasMany.html

答案 1 :(得分:0)

  

如果您希望自动维护数据透视表   created_at和updated_at时间戳,请使用withTimestamps方法   关系定义:

     

return $this->belongsToMany('App\Role')->withTimestamps();

Eloquent relationships.

多人关系中,withTimestamps()会自动为您管理时间戳。但是您正在实现有很多关系,因此可以直接访问时间戳。

在这种情况下,您可以在模型中使用访问器来格式化日期:

public function getCreatedAtAttribute()
    {
        return date("l jS \of F Y h:i:s A", strtotime($this->attributes['created_at']));
    } 
相关问题