【问题标题】:Call to a member function addEagerConstraints() on null在 null 上调用成员函数 addEagerConstraints()
【发布时间】:2023-03-14 22:06:02
【问题描述】:

我想按type_order 对查询进行排序:

public function posts()
{
    if (($this->type_order) == '1') {
        $type = 'id';
        return $this->belongsToMany(Post::class, 'feed_posts')->orderBy($type);
    }
}

但得到错误:

FatalThrowableError
Call to a member function addEagerConstraints() on null

【问题讨论】:

  • 你在哪里声明 posts() 方法?

标签: php laravel


【解决方案1】:

这是因为 Laravel 经常创建模型的空实例来构造查询/新实例。因此,当它创建一个新实例来构建查询时,posts() 实际上返回null 而不是BelongsToMany 关系。

要解决此问题,您必须删除条件并以另一种方式解决该问题。

【讨论】:

    【解决方案2】:

    尝试使用setType()这种方法来设置类型然后像这样调用$vaiable->setType()->posts;

    public $newType = 'id'; // default ordering is by id
    
    public function setType()
    {
        if (($this->type_order) == '1') {
            $this->newType = 'id';
        }
        return $this;
    }    
    
    public function posts()
    {
        $result = $this->belongsToMany(Post::class, 'feed_posts');
        return $result->orderBy($this->newType);
    }
    

    【讨论】:

      【解决方案3】:

      我有这个问题,因为我忘了返回

      class Test extends Model 
      {
          public function tests(){
             $this->hasMany(Test::class);
          }
      }
      

      【讨论】:

      • 这解决了我的问题
      • @mwangaben 很高兴为您提供帮助
      【解决方案4】:
      public function posts()
      {
          if (($this->type_order) == '1') {
              $type = 'id';
              return $this->belongsToMany(Post::class, 'feed_posts')->orderBy($type);
          }
          return false;
      }
      

      【讨论】:

        【解决方案5】:

        唯一的原因是,并非每次在 Laravel 关系方法中都可以访问 $this 对象,例如在重新渲染 Livewire 组件时 - 在你的关系方法中 $this 对象 将为空。在您的情况下,$this->type_order 可以为 null 而您没有 else 语句,这就是为什么 Call to a member function addEagerConstraints() on null

        【讨论】:

          猜你喜欢
          • 2022-01-08
          • 2020-12-29
          • 1970-01-01
          • 2020-07-26
          • 2018-12-17
          • 1970-01-01
          • 2021-12-10
          • 2017-08-09
          • 2020-03-10
          相关资源
          最近更新 更多