Php getAttribute中的关系数据

Php getAttribute中的关系数据,php,laravel,eloquent,Php,Laravel,Eloquent,我在Laravel中定义了一对多关系: 模块有许多模块,模块有一个模块 它工作得很好,但是我想在模块选项中设置一个名为url的自定义属性 要实现这一点,我需要以下代码: protected $appends = array('url'); public function getUrlAttribute() { $nameURL = SharedMethods::slugify($this->title); $url = "#/control/{$

我在Laravel中定义了一对多关系:

模块
有许多
模块
模块
有一个
模块

它工作得很好,但是我想在模块选项中设置一个名为
url
的自定义属性

要实现这一点,我需要以下代码:

  protected $appends = array('url');

  public function getUrlAttribute() {
      $nameURL = SharedMethods::slugify($this->title);
      $url = "#/control/{$module}/{$nameURL}/{$this->id}";
      return $url;
  }
到目前为止,一切正常,但是
$module
变量是空的,我只有
$this->moduleID
,它链接到
模块

我需要
$this->modules()->title
,但它在我的
getUrlAttribute
方法中不起作用

是否有任何方法可以访问
getAttribute
中的关系数据

编辑
模块选项
类中的关系为:

  public function TheModule() {
    return $this->belongsTo('App\TheModules');
  }
  public function TheActions() {
    return $this->hasMany('App\TheModulesActions', 'moduleID');
  }
模块
类中的关系为:

  public function TheModule() {
    return $this->belongsTo('App\TheModules');
  }
  public function TheActions() {
    return $this->hasMany('App\TheModulesActions', 'moduleID');
  }
已尝试
$this->模块->标题

给我这个错误:


modulesactions.php第15行出现错误异常:
试图获取非对象的属性

您可以通过删除关系名称上的括号
()
来获取该属性,如下所示:

$this->TheModules->title

当您将括号与关系名称一起使用时,Laravel将返回查询生成器的实例。

您可以通过在关系名称上删除括号
()
来执行此操作,如下所示:

$this->TheModules->title

当您将括号与关系名称一起使用时,Laravel将返回查询生成器的实例。

TheModulesActions.php第15行中的ErrorException:尝试获取非对象的属性能否在
TheModulesActions
类中显示关系?我希望您在
modulesactions
类中的关系名称是
TheModules()
。请确保您的数据库中有当前
TheModulesActions
的关系。您可以使用
dd($this->TheModules)
进行测试。如果返回
null
,则在定义关系时存在错误,或者数据库中没有关系。刚刚修复了该问题,该问题是错误的关系。这就是解决方案:
return$This->hasOne('App\TheModules','id','moduleID')模块选项.php第15行中的错误异常:尝试获取非对象的属性能否显示
模块选项
类中的关系?我希望您在
modulesactions
类中的关系名称是
TheModules()
。请确保您的数据库中有当前
TheModulesActions
的关系。您可以使用
dd($this->TheModules)
进行测试。如果返回
null
,则在定义关系时存在错误,或者数据库中没有关系。刚刚修复了该问题,该问题是错误的关系。这就是解决方案:
return$This->hasOne('App\TheModules','id','moduleID')