2

sorry for a newbie question. I run into a problem. I want to search the database for values which an in array. But I have an error:

Array to string conversion

And kinda get why but, I don't know how to make it right. Can you help me please? This is my code:

public function chassis($chassis){
    return $this->builder->whereIn('model_type_en', 'LIKE', (array)"%$chassis%");
}

P.S please don't laugh at me :)

gaurav
  • 657
  • 4
  • 11
Dmitry Malys
  • 1,293
  • 4
  • 25
  • 46
  • Like and where in are completely separate things. Builder will probably have method called like with two parameters fieldname and string. Use that without casting to array (array). – Maciej Paprocki Aug 17 '17 at 12:45
  • hard, I need to make a solution. People in application want to input many chassis numbers at one time and result should display all of them or at least similar to them – Dmitry Malys Aug 17 '17 at 12:47
  • The problem is mysql doesn't support in with array, instead you need to create multiple like statements joined by OR. However, please be aware, big amount of likes like that will make really inefficient query – Maciej Paprocki Aug 17 '17 at 12:53
  • @MaciejPaprocki yaa I kind of thinking to give up on LIKE, just use whereIN array – Dmitry Malys Aug 17 '17 at 12:58

3 Answers3

3
$collection = DB::table('your_table')->select('*');
foreach($chassis as $key=>$val) {
    if($key == 0) {
        $collection->where('model_type_en', 'like', "%$val%"));
    }
    $collection->orWhere('model_type_en', 'like', "%$val%"));
}
$name = $collection->get();

This may work. You can also look at the ref: laravel querybuilder how to use like in wherein function

(original wrong ans:)

If chassis is a string, you can do this:

$this->builder->where('model_type_en', 'LIKE', "%$chassis%");

You can read the docs: https://laravel.com/docs/5.4/queries

ch271828n
  • 15,854
  • 5
  • 53
  • 88
0

you can use as like be sure $chassis is an array

public function chassis($chassis)
{
    return $this->builder->whereIn('model_type_en', $chassis);
}
D Coder
  • 572
  • 4
  • 16
0

What you are tying to do is a combination of an IN and a LIKE.

I would suggest RLIKE which is a LIKE but with REGEX. Although this is mysql specific, so I doubt there is a Laravel build in way to do this.

Update

Sadly I was mistaken, and though RLIKE could do it. Instead find your answer in this post here : Is there a way to combine IN and LIKE in MySQL?

DarkMukke
  • 2,469
  • 1
  • 23
  • 31