【问题标题】:Laravel Eloquent relationships hasmany error: Call to undefined method when using on whereLaravel Eloquent 关系有很多错误:在 where 上使用时调用未定义的方法
【发布时间】:2021-08-22 14:24:58
【问题描述】:

我对 laravel eloquent 中的 hasmany 关系有疑问。为了理解我的问题,我将分享一些关于我的项目的信息。我有一个用户、工作区和项目模型。工作区模型与项目模型具有“多”关系。项目模型与工作空间模型具有“belongsTo”关系。

工作区模型:

class Workspace extends Model {
    
use HasFactory;

public function projects(): \Illuminate\Database\Eloquent\Relations\HasMany {
       return $this->hasMany(Project::class);
    }
  }

项目模型:

class Project extends Model

{
    use HasFactory;

    public function workspace(){
       return $this->belongsTo(Workspace::class, 'foreign_key');
   }
}

我正在尝试从登录用户那里检索所有工作区,这些项目属于工作区,在工作区控制器的索引函数中包含以下代码。

return Workspace::where('user_id', '=', 1)->projects()->get();

当这段代码运行时,我得到

BadMethodCallException 调用未定义的方法 Illuminate\Database\Eloquent\Builder::projects()

所以我的问题是:为什么 Laravel 给我一个错误的方法错误,我如何检索我的工作区及其属于某个用户的项目?

【问题讨论】:

    标签: php laravel eloquent model laravel-8


    【解决方案1】:

    应该是。你可以使用with method加载relationship data

    return Workspace::where('user_id', '=', 1)->with('projects')->get();
    

    为了更好地理解接受两个参数

     with($relations, $callback = null)
    

    回调帮助我们编写关系查询

    with 设置应该预先加载的关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 2017-10-30
      • 1970-01-01
      相关资源
      最近更新 更多