Laravel – 如何将参数传递给模型函数

huangapple go评论134阅读模式
英文:

Laravel - how to pass parameter to model function

问题

我有一个订单和商品表,我想通过传递参数到函数并在where子句中使用来获取数据。

  1. public function items()
  2. {
  3. return $this->belongsToMany(\App\Items::class, 'order_has_items', 'order_id', 'item_id')
  4. ->withPivot(['qty', 'extras', 'vat', 'vatvalue', 'variant_price', 'variant_name', 'id', 'kds_finished', 'created_at'])
  5. ->withTrashed();
  6. }
英文:

I have order and item table , I want to get the data by passing parameters to function and use in where in clause

  1. $this->order->custom_function($parameters);
  1. public function items()
  2. {
  3. return $this->belongsToMany(\App\Items::class, 'order_has_items', 'order_id', 'item_id')->withPivot(['qty', 'extras', 'vat', 'vatvalue', 'variant_price', 'variant_name','id','kds_finished','created_at'])->withTrashed();
  4. }

答案1

得分: 1

  1. {
  2. public function customFunction($parameters)
  3. {
  4. return $this->items()
  5. ->where(function ($query) use ($parameters) {
  6. // 根据参数应用筛选条件
  7. if (isset($parameters['some_filter'])) {
  8. $query->where('column_name', $parameters['some_filter']);
  9. }
  10. // 根据需要添加更多筛选条件
  11. })
  12. ->get();
  13. }
  14. public function items()
  15. {
  16. return $this->belongsToMany(\App\Items::class, 'order_has_items', 'order_id', 'item_id')
  17. ->withPivot(['qty', 'extras', 'vat', 'vatvalue', 'variant_price', 'variant_name','id','kds_finished','created_at'])
  18. ->withTrashed();
  19. }
  20. }

Controller

  1. $order = Order::find($orderId);
  2. $parameters = [
  3. 'some_filter' => 'some_value',
  4. // 根据需要添加更多参数
  5. ];
  6. $filteredItems = $order->customFunction($parameters);

请使用这段代码,并替换参数和字段,如果发现任何问题,请告诉我。

英文:
  1. {
  2. public function customFunction($parameters)
  3. {
  4. return $this->items()
  5. ->where(function ($query) use ($parameters) {
  6. // Apply filters based on parameters
  7. if (isset($parameters['some_filter'])) {
  8. $query->where('column_name', $parameters['some_filter']);
  9. }
  10. // Add more filters as needed
  11. })
  12. ->get();
  13. }
  14. public function items()
  15. {
  16. return $this->belongsToMany(\App\Items::class, 'order_has_items', 'order_id', 'item_id')
  17. ->withPivot(['qty', 'extras', 'vat', 'vatvalue', 'variant_price', 'variant_name','id','kds_finished','created_at'])
  18. ->withTrashed();
  19. }
  20. }

Controller

  1. $parameters = [
  2. 'some_filter' => 'some_value',
  3. // Add more parameters as needed
  4. ];
  5. $filteredItems = $order->customFunction($parameters);

please use this and replace the parameter and fields and let me know if any issues are found.

huangapple
  • 本文由 发表于 2023年8月10日 14:21:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定