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 :)
$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
you can use as like be sure $chassis is an array
public function chassis($chassis)
{
return $this->builder->whereIn('model_type_en', $chassis);
}
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?
Related
I'm trying use a whereIn inside a where array I am passing to Laravel query Builder:
$where = [['Participants.Client_Id','IN', $clientId]];
DB::table('Participants')->where($where)->get()
Something like is what I want to achieve, and I know there are works around such as using whereIn, but I'm sharing here a small piece of code to give you an idea, so I need to change the array to make it works as a whereIn, not changing the ->where to ->whereIn or ->whereRaw
DB::table('participants)->whereIn('Participants.Client_Id',$clientId)->get();
You must collect the IDs in the $clientId variables.
If I understand, you could do something like that :
$wheres = [['Participants.Client_Id','IN', [$clientId]]];
$query = DB::table('Participants');
foreach($wheres as $where) {
$query->where($where[0], $where[1], $where[2]);
}
$participants = $query->get();
As laravel document , you can use array in where and each element of this array must be a array with three value . So your $where variable is correct.
But as I searched in operator is not supported by query builder of where.
I am putting together a small mailing application within my application, and have run into a strange error - even just following the instructions for the advanced queries. I need to get -just- the mailboxes that are named:
$CoreMailboxes = TableRegistry::get('CoreMailboxes');
$query = $CoreMailboxes->find()
->where(function (QueryExpression $exp, Query $q) {
return $exp->isNotNull('name');
});
$query->hydrate(false);
return $query->toArray();
This is a near duplicate, sans "hydrate: false", of the example in the Cake Cookbook. However, it's giving me an error of
Argument 1 passed to App\Model\Table\CoreMailboxesTable::App\Model\Table\{closure}() must be an instance of App\Model\Table\QueryExpression, instance of Cake\Database\Expression\QueryExpression given
The query in the Cookbook is this:
$query = $cities->find()
->where(function (QueryExpression $exp, Query $q) {
return $exp->isNotNull('population');
});
What am I doing wrong?
You do not need to use the query expression for such a simple query..
You can just put the 'IS NOT NULL' in the where...
Now to re-use the query and create a more usable finder(), expressions may be more useful
$result = $this->Table->find()
->where([
'TableName.column_name IS NOT NULL'
])->toArray();
The problem is the instance definition's of your first argument, the doc is clear:
The passed anonymous function will receive an instance of \Cake\Database\Expression\QueryExpression as its first argument, and \Cake\ORM\Query as its second
Maybe you dont set the correct namespaces of this class, try this:
<?php
use \Cake\Database\Expression\QueryExpression as QueryExp;
//more code
//more code
->where(function (QueryExp $exp, Query $q) {
//more code
I've encounter today same error.
Try to add
use Cake\ORM\Query;
use Cake\Database\Expression\QueryExpression;
at beginning of your controller. It's help in my case.
I also try kip's answer but it doesn't work in my case
This is for Laravel 5.2. I have a method defined as follows in my Users model:
public function name()
{
return "$this->name_first $this->name_last";
}
I'm trying to figure out how to use that as part of a query, but it seems like it isn't possible for a somewhat obvious reason: the database doesn't know anything about the method and that makes perfect sense. However, the concept of what I'm trying to achieve makes sense in certain contexts, so I'm trying to see if there's a way to accomplish it naturally in Eloquent.
This doesn't work, but it represents what I'm trying to accomplish:
public function index(Request $request)
{
$query = new User();
if(Request::has('name')) {
$query = $query->where('name', 'LIKE', '%' . Request::input('name') . '%');
}
return $query->get();
}
In short, the database only knows about name_first and name_last, but I'd like to be able to search (and sort) on name without storing it. Maybe storing the concatenated name is no big deal and I should just do it, but I'm also trying to learn.
I agree with Bogdan, The issue of having spaces either in the first or the last name makes querying on the individual columns difficult, so this is probably the way to go. Code reuse can be increased by defining it as a custom scope:
https://laravel.com/docs/5.2/eloquent#local-scopes
// class User
public function scopeOfFullNameLike($query, $fullName)
{
return $query->whereRaw('CONCAT(name_first, " ", name_last) LIKE "%?%"', [$fullName]);
}
// ...
User::ofFullNameLike('john doe')->get();
That would mean you should be concatenating the column value at the database level. Which means you could use CONCAT and a whereRaw clause:
$query->whereRaw('CONCAT(name_first, " ", name_last) LIKE ?', ['%' . Request::input('name') . '%']);
Or as an alternative if you want the full name to be selected as part of the result, you could concatenate within the select and use having instead of where to be able to use a column alias:
$query->select('*', DB::raw('CONCAT(name_first, " ", name_last) as name'))
->having('name', 'LIKE', '%' . Request::input('name') . '%');
Not the most compact solutions, but things involving MySQL functions need some raw SQL to work with the Query Builder.
Sorry if my title is confusing, not sure how to explain this within a line. Let's say I have a table with some columns and I have this
$model = Document::where('systemName', '=', $systemName)->where('ticketNumber', '=', ($nextTicketNumber))->get(); ticketNumber is unique where as there are quite a few systemNames
The above will get exactly what I want but I want more. I want an another array which will store all the rows under the same systemName. I know I can do this by doing
$allSystemNameModel = Document::where('systemName', '=', $systemName)
But is there a possible way to not having two variables and be easier?
No, you can't get both collections into one variable with one statement, however, you can create an array and store your results there:
$both = [];
$both['model'] = ...
$both['all'] = ...
UPDATE:
To avoid querying the database twice, you can use a first method that laravel provides us with.
$allSystemNameModel = Document::where('systemName', '=', $systemName);
$model = $allSystemNameModel->first(function ($doc) use ($nextTicketNumber) {
return $doc->ticketNumber == $nextTicketNumber;
});
$both['model'] = $model;
$both['all'] = $allSystemNameModel->all();
Note: Be sure to use use when working with php closures since $nextTicketNumber will be undefined otherwise.
I have a research to do in a database. Not always I'll be using all of parameters. The user may want to research for a name, but not address or the other way around.
I've tried to use advanced wheres and even unions, but none seems to work. All of them give me a SQL error "General error: 1221 Incorrect usage of UNION and ORDER BY".
Here's a piece of code I've tried
$city_name = ($city_name != null) ? DB::table('cities')->where('name', 'LIKE', "%$city_name%") : DB::table('cities');
$state = ($state_id != '--') ? DB::table('cities')->where('state_id', '=', $state_id) : DB::table('cities');
$cities = DB::table('cities')->union($city_name)->union($state)->orderBy('name')->get();
But it gives me the above described error.
What I really want to do is to select, dinamically, what parameters I put in the query and even assemble it "on the fly". Does anyone knows how to do that?
If I couldn't make myself clear, please let me know in the comments...
I think you need somethink like this:
$query = DB::table('cities');
if ($city_name != null)
{
$query->where('name', 'LIKE', "%$city_name%");
}
if ($state_id != '--')
{
$query->where('state_id', '=', $state_id);
}
$cities = $query->orderBy('name')->get();