如何将带参数的Laravel模型函数调用到Vue Js中(用于计算库存数量)?

How to call Laravel Model function with parameter into Vuejs (for calculating stock Qunatity)?

我有三个型号1.Fertilizer,2.化肥库存,3.Fertilizer销售。 2 & 3 有外键 relation(fertilizer_id) & mysql quantity column 。 我想在我的肥料模型中计算单个肥料库存数量,并在惯性索引页面中附加肥料控制器。我的代码有什么问题?

Controller

    /**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index( Request $request)
{
    return Inertia::render('Fertilizers/Index', [
        'fertilizers' => Fertilizer::with('stocks')
        ->filter($request->all())
            ->sorted()
            ->paginate()
            ->withQueryString(),
        'query'  => $request->all(),
    ]);
}

Model

    protected $appends = ['stocks'];
/**
 * Determines one-to-many relation
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function units()
{
   return $this->belongsTo(Unit::class);
}

Stock Function

public function getStocksAttribute(){
$stock_quantity = FertilizerStock::where(['fertilizer_id', $this->id])->sum('quantity');
$sale_quantity = FertilizerSell::where(['fertilizer_id', $this->id])->sum('quantity');
return $stock_quantity - $sale_quantity;}

将此添加到您的肥料模型中。

    public function getStockAttribute()
{
    $fertilizerId= $this->id;
    $fertilizerStock = FertilizerStock::where('fertilizer_id',$fertilizerId)->sum('quantity');
    $fertilizerSells = FertilizerSell::where('fertilizer_id',$fertilizerId)->sum('quantity');
    return $fertilizerStock-$fertilizerSells;
}