Laravel主动运输方式

问题描述

表格:

       Schema::create('shippings',function (Blueprint $table) {
            $table->id();
            $table->string('name',64);
            $table->integer('price');
            $table->enum('active',['yes','no'])->default('yes');
            $table->timestamps();
        });
    }

型号:

class Shipping extends Model
{
    const YES = 'yes';
    const NO = 'no';

    public function isActive()
    {
        return $this->active == self::YES;
    }
}

我想通过使用这样的模型函数显示活动的

 $shipping = Shipping::with('isActive')->get();

但是我得到了

错误 在bool上调用成员函数addEagerConstraints()

我做错什么了吗,还是不可能以这种方式做到这一点?

解决方法

您可以使用laravel scopes代替:

class Shipping extends Model
{
    const YES = 'yes';
    const NO = 'no';

    public function scopeActive($query)
    {
        return $query->where('active','=',self::YES);
    }
}

然后

$shipping = Shipping::active()->get();