我想在PHP代码中添加一个sql过滤器where('comment_id', '=', 1)
$datas = $this->model->ADD HERE->orderBy('created_at', 'DESC')->paginate(15);
尝试将字符串添加到代码需要几个小时。如何制作?
这是我的代码:
CommentResource.php将sql过滤器作为字符串参数传递。
<?php
class CommentResource extends BaseResource
{
public function index()
{
$filter = "where('comment_id', '=', 1)";
return parent::index_filter($filter);
}
CommentResource.php
<?php
class BaseResource extends Controller
{
protected function index_filter($filter)
{
$datas = $this->model->ADD HERE->orderBy('created_at', 'DESC')->paginate(15);
return view($this->resourceView.'.index')->with('datas', $datas);
}
}
答案 0 :(得分:0)
我不确定我是否正确地满足了您的要求,但如果您重写index_filter以分别接受field
和value
,那么您可以从laravel中使用常规where()
:
protected function index_filter($field,$value)
{
$datas = $this->model->where($field,$value)->orderBy('created_at', 'DESC')->paginate(15);
return view($this->resourceView.'.index')->with('datas', $datas);
}
您可以找到文档here。如果你真的需要更多的灵活性:
protected function index_filter($filter)
{
$datas = $this->model->whereRaw($filter)->orderBy('created_at', 'DESC')->paginate(15);
return view($this->resourceView.'.index')->with('datas', $datas);
}
请注意,虽然这是非常危险的,因为你暴露了注入恶意代码的可能性,但它应该事先正确地进行转义。
答案 1 :(得分:0)
据我所知,您希望在查询中使用不同类型的过滤器作为过滤器。这就是为什么你想让它们变得动态的原因。我会为您的任务建议以下解决方案:
<?php
class CommentResource extends BaseResource
{
public function index()
{
$filter = [ 'operator' => 'where', 'args' => ['comment_id', '=', 1]];
return parent::index_filter($filter);
}
<?php
class BaseResource extends Controller
{
protected function index_filter($filter)
{
$where = $filter['operator'];
$args = $filter['args'];
$datas = $this->model->$where(...$args)->orderBy('created_at', 'DESC')->paginate(15);
return view($this->resourceView.'.index')->with('datas', $datas);
}
}
但是,由于oeprator ...
答案 2 :(得分:0)
我的最新代码正常。我会在这里发帖。
<?php
class CommentResource extends BaseResource
{
public function index()
{
$options = [
'filters'=>[
[ 'operator' => 'where',
'args' => [
[ 'article_id', '=', $article_id ],
[ 'comment_id', '=', $comment_id ],
// add filter args...
],
],
// add filter operators here...
],
'sorts' => [
'column' => $sortColumn, // change sort column...
'order' => $sortOrder, // change sort order...
],
];
return parent::index_filter($options);
}
<?php
class BaseResource extends Controller
{
protected function index_filter($options, $number=15)
{
$result = $this->model;
foreach ($options['filters'] as $filter) {
$operator = $filter['operator'];
$args = $filter['args'];
$result = $result->$operator($args);
}
if ( $options['sorts'] != [] ) {
$column = $options['sorts']['column'];
$order = $options['sorts']['order'];
$result = $result->orderBy($column, $order);
}
return $result->paginate($number);
}
}
我更改的原因... $ args为$ args,当'args'超过值时,例如,
'args' => [
[ 'article_id', '=', $article_id ],
[ 'comment_id', '=', $comment_id ],
// add filter args...
],
... $ args会将'args'更改为一个数组,但是$ args将保持'args'为nest数组,这就是运算符'所需'。