Closed pokemonhan closed 4 years ago
Depending on how complex that json input can get you can filter raw json a couple of different ways.
Let's say you have filter input of:
MyModel::filter(['json_input' => '{"id":1,"status":0}'])->get();
You can create just one method that will handle this json:
public function jsonInput(string $json)
{
$data = \json_decode($json, true);
return $this->where('inputs->id', $data['id'])
->where('inputs->status', $data['status']);
}
Or if you want to take advantage of individual methods you can merge the input in a setup
method that gets called before any filtering happens to make the input available to all filter methods:
// The filter looks for a method called `setup`
// defining one ensures this is called before any filtering happens
public function setup()
{
if($json = $this-input('json_input')) {
$this->push(\json_decode($json, true));
}
}
public function id($id)
{
return $this->where('inputs->id', $id);
}
public function status($status)
{
return $this->where('inputs->status', $status);
}
Or if you wanted to prefix your json methods you could do that in your setup method too:
public function setup()
{
if($json = $this->input('json_input')) {
foreach(\json_decode($json, true) as $key => $val) {
// When these values are passed to filter methods
// the methods will be based off these prefixed keys
$this->push('json_' . $key, $val);
}
}
}
public function jsonId($id)
{
return $this->where('inputs->id', $id);
}
public function jsonStatus($status)
{
return $this->where('inputs->status', $status);
}
I hope this helps! Let me know if I can clarify anything!
Cheers!
I like this way, thank you very much for sharing me knowledge.
Question: How to Naming method names for json fields here is field name inputs with json type in table
I don't know by writing this way is ok or not.
please also support for json field filtering method if possible.