如何使用计算值,就像它是Laravel模型中的列值一样?

Mut*_*iti 5 php laravel

我有一个项目模型,看起来像这样:

class Product extends Model
{
    public $timestamps = true;
    protected $guarded = ['id'];
    protected $table = 'products';
    protected $hidden = ['created_at', 'updated_at'];
    protected $fillable = ['name', 'category_id', 'units', 'b_price', 's_price', 'warn_count', 'added_by'];

    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function stock(){
        $product_id = $this->id;
        $filter = ['product_id' => $product_id];
        //STOCK PLUS
        //credit purchases
        $cr_purchases = CreditPurchase::where($filter)->sum('qty');
        //purchases
        $purchases = Purchase::where($filter)->sum('qty');
        //returns in
        $re_in = ReturnIn::where($filter)->sum('qty');
        //STOCK MINUS
        //credit sales
        $cr_sales = CreditSale::where($filter)->sum('qty');
        //sales
        $sales = Sale::where($filter)->sum('qty');
        //returns out
        $re_out = ReturnOut::where($filter)->sum('qty');
        //damaged
        $damaged = DamagedProduct::where($filter)->sum('qty');
        return $cr_purchases + $purchases + $re_in - ($cr_sales + $sales + $re_out + $damaged);
    }
}
Run Code Online (Sandbox Code Playgroud)

可以看出,库存是每个模型的计算值.我希望基于它进行查询,就好像它是products表的一列.

小智 3

方法 1
将 stock 方法更改为 Laravel 模型访问器。

public function getStockAttribute(){
   //code logic
}
Run Code Online (Sandbox Code Playgroud)

以集合形式获取结果并对“stock;”执行过滤器 属性
我会做类似的事情。

Products::where('product','like','miraa') //where
->get()
->filter(function($item) {
    return $item->stock > 100;
});
Run Code Online (Sandbox Code Playgroud)

了解过滤集合

方法 2
使用动态查询作用域 请参阅laravel 中的作用域。

public function scopeAvailbaleStock($query, $type)
{
    return $query->where('type', $type);
    // could perform filters here for the query above
}
Run Code Online (Sandbox Code Playgroud)

使用范围获取

$users = Products::available_stock()->get();
Run Code Online (Sandbox Code Playgroud)

方法3 我看到了这个包jarektkaczyk/eloquence

public function scopeWhereStock($query, $price, $operator = '=', $bool = 'and'){
    $query->where('info1', $operator, $price, $bool);
   }

// then
Products::whereStock(25); // where('info1', 25);
Products::whereStcok(25, '>'); // where('info1', '>', 25);
Products::whereStock(25, '=', 'or'); // orWhere('info1', 25);
Run Code Online (Sandbox Code Playgroud)

但是,我建议使用方法 1 或 2。第三种解决方案有效,但不确定它是否是最好的