Php 在null上调用成员函数addagerConstraints()

Php 在null上调用成员函数addagerConstraints(),php,laravel,Php,Laravel,我想按类型\u顺序对查询进行排序: public function posts() { if (($this->type_order) == '1') { $type = 'id'; return $this->belongsToMany(Post::class, 'feed_posts')->orderBy($type); } } 但是得到错误: FatalThrowableError Call to a member fun

我想按
类型\u顺序对查询进行排序

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

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


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

之所以会出现这种情况,是因为Laravel经常创建模型的空实例来构造查询/新实例。因此,当它创建一个新实例来构建查询时,
posts()
实际上返回
null
,而不是
belongToMany
关系

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

尝试使用
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);
}
尝试使用
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);
}

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

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

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

class Test extends Model 
{
    public function tests(){
       $this->hasMany(Test::class);
    }
}
在哪里声明posts()方法?在哪里声明posts()方法?