I want to find by letter customer's first_name on my 'customers' table.
And the only thing that I get is an empty array.
For instance, I put in the parameter 'q' value 'E' to get customer Elena from my database by I get an only empty array.
I use the following code to get first_name :
$search = Input::get('q');
if($search)
{
$customers = Customer::all()->where('full_name', 'LIKE', "%{$search}%");
return ($customers);
}
Can someone help me?
Your query don't work because you are calling the all() method before the where(). That's actually not wrong, but it have different behavior.
When you call all(), it actually does the SQL query. After that, any chained methods are being called into a Eloquent Collection class, and it also have a where method, but that's simpler since it runs on PHO instead of running on SQL.
Since the collection's where() method doesn't support LIKE operator, it's probably searching for a value that is exactly %E%.
Hope it can help you understanding why your query doesn't work as expected.
Try this
$customers = Customer::where('full_name', 'LIKE', "%{$search}%")->get();
Laravel Eloquent
Related
This is my model function now its working correctly, but i want to check where (or) orwhere. I Already try that but cant get the apt answer
public static function getPlacementCountByStatus(){
$countStatus = DB::table('placements')->where('status','1')->select(DB::raw('count(joborderid) as total, joborderid'))->groupBy('joborderid')->get();
return $countStatus;
}
I want to check something like this
->where('statusid','=','3')->orWhere('statusid','=','4')->orWhere('stageid','=','4')->orWhere('stageid','=','8');
// i want to check this in my $countStatus something like and or condition in my db::raw query
Use where() closure:
$countStatus = DB::table('placements')->where(function($q){
$q->where('statusid','=','3')->orWhere('statusid','=','4')->orWhere('stageid','=','4')->orWhere('stageid','=','8');
})
->select(DB::raw('count(placementid) as total,statusid'))
->groupBy('statusid')->get();
return $countStatus;
From the docs
Sometimes you may need to create more advanced where clauses such as
"where exists" clauses or nested parameter groupings.
In your case, you need to use where closure as you are trying to combine AND,OR operation, means you are trying to group your parameters in a block. Here closure mainly does what a parenthesis does in a sql query.
I'm trying to get the most recent record for each candidate_id from a ìnterviews` table.
This is what I want to achive:
I'm using Eloquent on laravel and have already tried this methods (with and without eloquent):
$candidates = DB::table('interviews')->select('interviews.*', 'i2.*')
->leftJoin('interviews as i2',
function ($join) {
$join->on('interviews.candidate_id', '=', 'i2.candidate_id');
$join->on('interviews.created_at', '<', 'i2.created_at');
}
)
->whereNull('i2.candidate_id')
->get();
and with eloquent I've tried this:
$candidates = Interview::leftJoin('interviews as i2',
function ($join) {
$join->on('interviews.candidate_id', '=', 'i2.candidate_id');
$join->on('interviews.created_at', '<', 'i2.created_at');
}
)->whereNull('i2.candidate_id')
->get();
If I change get() to toSql() I have exactly the same query that's shown on the above image, but running on laravel I'm getting always these results (this using the first method, with query builder):
Anyone know why I get this results? Is hard to understand that laravel is doing the same query that I do in HeidiSql but I get diferent results :(
Any tip?
Thanks in advance!
Because you are using ->select('interviews.*', 'i2.*') combined with ->whereNull('i2.candidate_id') I am assuming the second select parameter is overriding all fields on the interviews table with nulls, try reversing the order to ->select('i2.*','interviews.*') or not use the i2.* at all.
This is because the output ignores the alias and only uses the fieldname as element key in the returned collection.
Hope it works.
Perfect case scenario you pick the exact columns you want from each of the joined tables for e.g. it may go like this: table1.id,table1.column1,table1.column2,table2.column2 as smth_so_it_doesnt_override
the code below is executed but it brings a wrong records(all records in my table) , it's like he doesn't take on consideration the clause where
$result = $this->Posts->query('SELECT * FROM POSTS WHERE id=1');
I know that I can do it easily with find() but for some reasons I want to write the sql statement and to have the right results
Thanks for helping me.
query() method does not take any parameter. you can use it like
$data= $this->Posts->query()
->where(['id'=>1])
->execute()
->fetchAll();
So i have this code wish is supposed to retrieve me some view for a web service.
$records = Publication::all();
if(isset($headers["input"]["from"])) {
$from = Carbon::createFromFormat('Y-m-d', $headers["input"]["from"])->toDateTimeString();
$records = $records->where("created_at", ">", $from);
}
if(isset($headers["input"]["until"])) {
$until = Carbon::createFromFormat('Y-m-d', $headers["input"]["until"])->toDateTimeString();
$records = $records->where("created_at", "<", $until);
}
This should return me some publications when passing a GET argument of 2015-07-21 already... But it returns nothing. I tried testing to see what was going on doing a dd($results) after the code but i got nothing on any way i have tried. I tried passing ->get() and ->all() and still got nothing. I even tried calling only the method and not assign to the same $record variable although it did not make sense to me i was all in about fixing this.
Maybe is a problem with Sql Statement? Comparing dates? Carbon variables look fine when dd($until) or dd($from)
EDIT: Since i needed this to work i explored other ways... What i did was transform Publication::all() to Publication::query() ( this will get you QueryBuilder ) Then i worked with Query Builder ->where(field,comparison,value) and then finally retrieved the result with $records->get(); That Way you will still get the Model Collection because if you use DB::table('publications') and then the same code when you do ->get() you will only get the array of elements and no relationship loading like in model. Hope i made my point and explained well. And sorry if i did not. I really tried my best. This is now SOLVED!
Since i needed this to work i explored other ways... What i did was transform Publication::all() to Publication::query() ( this will get you QueryBuilder ) Then i worked with Query Builder ->where(field,comparison,value) and then finally retrieved the result with $records->get(); That Way you will still get the Model Collection because if you use DB::table('publications') and then the same code when you do ->get() you will only get the array of elements and no relationship loading like in model. Hope i made my point and explained well. And sorry if i did not. I really tried my best. This is now SOLVED!
Im new to Laravel, but am struggling with how Eloquent queries can have optional sections.
I have the following Eloquent query at the moment:
Posts::where('approved', '=', 'Y')->orderBy('created_at', 'DESC')->take($noofposts)->skip($skipno)->get();
That works fine. However I now need to add two optional sections, which i'd like to do without having to duplicate the query each time.
I need to add AND WHERE userid=$x (looped for one or more times) if $x (which is an array) is present, if its not it should ignore then ... and finally add AND (WHERE status=$y[0] OR $status=$y[1] OR $status=$y[2]) - again if the status flags are not set, then just ignore.
Basically if no flags are set I end up with the original query, but if they are we get
Posts::where('approved', '=', 'Y')->where('userid', '=', '2')->where('userid', '=', '23')->where('status', '=', 'K')->orWhere('status', '=', 'N')->orderBy('created_at', 'DESC')->take($noofposts)->skip($skipno)->get();
I can work it out perfectly in normal PHP, but cannot understand how it would work in Laravel Eloquent.
Can anyone point me in the right direction? Neither the user guide nor any website examples seem to look at this kind of scenario!
Fist, instead of chaining orWhere I would use the whereIn function of Eloquent.
whereIn('status', $y);
The problem is, if $y is empty, the request won't work. (I think it just crashes)
So if you want to avoid controls and keep your code clean you can add a query scope in you Post model.
http://laravel.com/docs/4.2/eloquent#query-scopes
scopeOptionalWhereIn($query, $field, $array){
if(!empty($array))
return $query->whereIn($field, $array);
return $query; //return unchanged query
}
Then you can use this scope in your query:
Posts::where('approved', '=', 'Y')
->optionalWhereIn('status', $y)
->orderBy('created_at', 'DESC')
->take($noofposts)
->skip($skipno)->get();
You can probably use the same scope to deal with the userid conditions.