代码之家  ›  专栏  ›  技术社区  ›  Solomon Antoine

调用undefined方法Illumb\Database\Eloquent\Relations\HasMany::withTimestamps()

  •  0
  • Solomon Antoine  · 技术社区  · 7 年前

    我正试图在拉拉维尔建立一种带有时间戳的关系。我有一个应用程序,允许客户向市场申请工作。当市场上的自由职业者找到他们感兴趣的工作时,他们建议完成该工作,并在自由职业者表中查询一个新行。

    以下是创建关系的代码:

    $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() 但我更愿意利用拉威尔提供的东西。有人有什么建议吗?

    注:我在这里提到了之前的一个问题: Timestamps are not updating while attaching data in pivot table 但不幸的是,这没有帮助。

    2 回复  |  直到 7 年前
        1
  •  5
  •   Angad Dubey    7 年前

    withTimestamps(); 在多对多关系中使用,在多对多关系中,您希望声明联接表中有created_at和updated_at列。

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

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

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

        2
  •  0
  •   Elisha Senoo    7 年前

    如果希望透视表自动维护 在时间戳处创建和更新,请在上使用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']));
        } 
    
    推荐文章