英文:
Laravel - how to pass parameter to model function
问题
我有一个订单和商品表,我想通过传递参数到函数并在where
子句中使用来获取数据。
public function items()
{
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();
}
英文:
I have order and item table , I want to get the data by passing parameters to function and use in where in clause
$this->order->custom_function($parameters);
public function items()
{
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();
}
答案1
得分: 1
{
public function customFunction($parameters)
{
return $this->items()
->where(function ($query) use ($parameters) {
// 根据参数应用筛选条件
if (isset($parameters['some_filter'])) {
$query->where('column_name', $parameters['some_filter']);
}
// 根据需要添加更多筛选条件
})
->get();
}
public function items()
{
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();
}
}
Controller
$order = Order::find($orderId);
$parameters = [
'some_filter' => 'some_value',
// 根据需要添加更多参数
];
$filteredItems = $order->customFunction($parameters);
请使用这段代码,并替换参数和字段,如果发现任何问题,请告诉我。
英文:
{
public function customFunction($parameters)
{
return $this->items()
->where(function ($query) use ($parameters) {
// Apply filters based on parameters
if (isset($parameters['some_filter'])) {
$query->where('column_name', $parameters['some_filter']);
}
// Add more filters as needed
})
->get();
}
public function items()
{
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();
}
}
Controller
$parameters = [
'some_filter' => 'some_value',
// Add more parameters as needed
];
$filteredItems = $order->customFunction($parameters);
please use this and replace the parameter and fields and let me know if any issues are found.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论