Laravel Eloquent relationships hasmany error: Call to undefined method when using on where

Laravel Eloquent relationships hasmany error: Call to undefined method when using on where

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

工作区模型:

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 Call to undefined method Illuminate\Database\Eloquent\Builder::projects()

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

应该be.You可以使用with method加载relationship data

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

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

 with($relations, $callback = null)

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

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