在雄辩的查询结果上使用特质
我正在使用Laravel 8。我想根据雄辩的查询结果使用我特征的功能。
这是我的特征:
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Collection;
trait MyTrait
{
public function myFunction(Collection $collection): array
{
// Some code and loop on $collection param
return [];
}
这是我实际使用它的方式:
public function index()
{
$data = MyModel::get(['id', 'value']);
$model = new MyModel();
return response()->json($model->myFunction($data), 200);
}
它有效,但我不喜欢此刻创建对象的实例。有一种方法可以直接将myfunction($ data)
直接应用于查询结果?像这样:
public function index()
{
$data = MyModel::get(['id', 'value'])->myFunction();
return response()->json($data, 200);
}
如果可能的话,那将是非常酷的,因为我不必发送任何参数,我只需要取出查询的结果即可。
I'm using Laravel 8. I want to use a function from my trait on the result of eloquant query.
Here is my trait:
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Collection;
trait MyTrait
{
public function myFunction(Collection $collection): array
{
// Some code and loop on $collection param
return [];
}
Here is how I use it actually:
public function index()
{
$data = MyModel::get(['id', 'value']);
$model = new MyModel();
return response()->json($model->myFunction($data), 200);
}
It works but I don't like to create an instance of the object at this moment. There is a way to apply myFunction($data)
directly to the result of the query ? Like that :
public function index()
{
$data = MyModel::get(['id', 'value'])->myFunction();
return response()->json($data, 200);
}
If this way is possible it will be very cool because I don't have to send any parameters and I just have to take the result of the query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于这样做,您可以在集合课上添加一个宏,但是据我所知,您需要操纵查询结果并将其在响应中使用。
laravel资源收集 完成工作。
在您的控制器中,您只需要使用您的资源收集
For doing though you can add a macro to the collection class, but as far as i see you need to manipulate result of query and use them in your response.
Laravel Resource collection does the job.
and in your controller you only need to use your resource collection