在null上调用成员函数addEagerConstraints()

时间:2017-09-18 07:54:56

标签: php laravel

我希望按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

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

尝试使用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);
}
相关问题