[英]Call to a member function addEagerConstraints() on null
I want to sort query in relation by type_order
:我想按
type_order
对查询进行排序:
public function posts()
{
if (($this->type_order) == '1') {
$type = 'id';
return $this->belongsToMany(Post::class, 'feed_posts')->orderBy($type);
}
}
But get error:但是得到错误:
FatalThrowableError
Call to a member function addEagerConstraints() on null
I had this issue because i forgot to return 我遇到了这个问题,因为我忘了回来
class Test extends Model
{
public function tests(){
$this->hasMany(Test::class);
}
}
This happens because Laravel often creates an empty instance of your model to construct queries/new instances. 发生这种情况是因为Laravel通常会创建模型的空实例来构造查询/新实例。 So when it creates a new instance to build a query,
posts()
actually returns null
instead of a BelongsToMany
relation. 因此,当它创建一个新实例来构建查询时,
posts()
实际上返回null
而不是BelongsToMany
关系。
To fix this you'll have to remove the conditional and solve that issue in another way. 要解决此问题,您必须删除条件并以另一种方式解决该问题。
try use setType()
kind of method to setting type then call like this $vaiable->setType()->posts;
尝试使用
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);
}
public function posts()
{
if (($this->type_order) == '1') {
$type = 'id';
return $this->belongsToMany(Post::class, 'feed_posts')->orderBy($type);
}
return false;
}
The only reason is that not everytime inside your Laravel relation method you can access to $this
object, for example on re-rendering Livewire component - in your relation method $this
object will be empty .唯一的原因是,并非每次在您的 Laravel 关系方法中您都可以访问
$this
object,例如在重新呈现Livewire组件时 - 在您的关系方法中$this
object将为空。 In your case $this->type_order
can be null and you don't have else statement, thats why Call to a member function addEagerConstraints() on null
在你的情况下
$this->type_order
可以是 null并且你没有其他声明,这就是为什么Call to a member function addEagerConstraints() on null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.