Laravel 4 eloquent WHERE with AND and OR? - laravel-4

How do I say WHERE (a=x AND b=y) OR (c=z AND d=j)
For x , y , z .. are variables .
How can i do that with eloquent ?

for multiple where statements use:
$result = Model::whereRaw('(a = ? and b=?) or (c=? and d=?)', ['x','y','z','j'])->get();

You can achieve this by passing a closure into the where() function of the query builder. This is covered in the advanced wheres section of the docs http://laravel.com/docs/5.0/queries#advanced-wheres
$results = MyModel::where(function($query) {
$query->where('a', 'x')
->where('b', 'y');
})->orWhere(function($query) {
$query->where('c', 'z')
->where('d', 'j');
})->get();

Related

Laravel 8 - How I do where clause in table added with join

Hi I want to know how can i do this query in Laravel 8 , I tried adding the join clause but not work as expected, i need join clause? Or maybe there is another form to do it. I search others examples but i donĀ“t see anythat help me. The query is the next:
DB::table('escandallo_p as esc')
->select("esc.material", "esc.referencia", "esc.ancho", "esc.proveedor", "esc.punto",
"esc.precio", "esc.consumo", "esc.veces", "esc.001", "esc.002", "esc.003", "esc.004",
"esc.005", "esc.006", "esc.007", "esc.008", "esc.009", "esc.010", "esc.011", "esc.um", "esc.merma", "esc.importe", "esc.tipo", "esc.xtalla", "esc.fase",
DB::raw("(select anulado from prototipos_p as p where p.prototipo = '".$scandal[0]->prototipo."' and p.tipo = 'c' and p.referencia = esc.referencia )"),
// ignore
//original query "(select anulado from prototipos_p as p where p.prototipo = ",$request->prototipo," and p.tipo = 'c' and p.referencia = esc.referencia ) as 'anulado'",
// "(select clase from prototipos_p as p where p.prototipo = ",$request->prototipo," and p.tipo = 'c' and p.referencia = esc.referencia ) as 'clase'")
//Converted query ->select('pro.anulado')->where('pro.prototipo', $request->prototipo)
// ->where("p.prototipo", "=", $request->prototipo)
->where("esc.id_escandallo", "=", $request->id_escandallo)
->where("esc.id_version", "=", $request->version)
->orderBy("id","asc")
->get();
!!!! I need to pass the esc.referencia to the sub select query
The second select is the conversion of the select inside "" ( i know this is wrong is only for explain it).
Thank you in advance for any suggestion.
Best regards
EDIT: I can solve my problem with DB::raw, but if anyone know others methos are welcome!
You need to pass callback to the join query to add the extra query to the laravel's join method,
Example from Laravel Doc:
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')
->where('contacts.user_id', '>', 5);
})
->get();
It is explained in Laravel's doc, Advanced Join Clauses
There is Subquery support too Subquery Joins,
Eg:
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})
->get();
These two might help you to achieve what you are trying
After test joins, joinSub, whereIn and other forms of doing this, I solved my problem using the DB::raw():
DB::table('escandallo_p as esc')
->select('parameters',....,
DB::raw("(SELECT column //(ONLY ONE)
FROM table
WHERE column = '".$parameter."' ...) AS nombre"),
)
->where('column', "=", $parameter)
->orderBy("id","asc")
->get();

Laravel 8, whereRelation take the where value condition from model

i'm using whereRelation but i do not know
how to take the where value condition from the base model
I have tried this code:
Item::with('unit','stock')->whereRelation('stock', 'stock', '<', 'items.min_stock');
and query result in debugger :
select * from `items` where exists (select * from `stocks` where `items`.`id` = `stocks`.`id_item` and `stock` < 'items.min_stock')
The query result i wanted :
select * from `items` where exists (select * from `stocks` where `items`.`id` = `stocks`.`id_item` and `stock` < `items`.`min_stock`)
'items.min_stock' it become like a string, How can i solve this ?
Otherize you can use whereHas method, example below:
Item::with('unit', 'stock')->whereHas('stock', function ($query) {
$query->where('stock', '<', DB::raw('items.min_stock'))
});
I found solution for my code
i change my code like this and it's works
Item::with('unit','stock')->whereRelation('stock', 'stock', '<', DB::raw('items.min_stock'));
thanks to #Vildan Bina for the answer
Try using whereRaw
Item::with('unit','stock')->whereRelation('stock', function (Builder $query) {
$query->whereRaw('stock < items.min_stock'); // semicolon
});

Laravel 5.6: how to create a subquery using Query Builder

I would like to reproduce following mySQL query using Laravel query builder:
*SELECT SUM(scores) FROM (SELECT scores FROM player_games WHERE player_id = 1 ORDER BY id DESC LIMIT 2) scores
Any suggestions?
Here the solution:
$sub = playerGame::where('player_id',1)->where('scores','>',0)->limit(2)->orderBy('id','desc');
$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
->mergeBindings($sub->getQuery())
->sum('scores');
return $count;
Use fromSub():
$sub = playerGame::select('scores')
->where('player_id', 1)
->where('scores', '>', 0)
->limit(2)
->orderBy('id','desc');
$sum = DB::query()->fromSub($sub, 'scores')->sum('scores');
$responce= DB::table('player_games')->where('player_id',1)->sum('amount');
dd(collect($responce)->sortByDesc('id')->take(2));
please cheack this one.....i try it's work....and add use DB;in the top of controller....

How can I build has single query in laravel

$tadaydate = ddate('m/d/Y');
$value1 = value_table::where('value_1', $tadaydate)->get();
$value2 = value_table::where('value_2', $tadaydate)->get();
$value3 = value_table::where('value_3', $tadaydate)->get();
$value4 = value_table::where('value_4', $tadaydate)->get();
$value5 = value_table::where('value_5', $tadaydate)->get();
Is there any chance to check with single query?
You can use the "->whereIn()" function I believe.
$value_array = ['value1',...,'value5'];
$value_table->whereIn($tadaydate, $value_array)->get;
You can combine then:
$query = value_table::where('value_1',$tadaydate)
->orWhere('value_2',$tadaydate)
->orWhere('value_3',$tadaydate)
->orWhere('value_4',$tadaydate)
->orWhere('value_5',$tadaydate)
->get()
You should use where instead of orWhere to connect the wheres with an AND instead of an OR
To simplify it in a loop:
$columns = 7;
$query = value_table::query();
for ($i = 1;$i <= $columns;$i++) {
$query = $query->orWhere('value_'.$i,$tadaydate);
}
$values=$query->get();
However you will have much more success if you normalise your table:
table
-----------
id | more columns
value_table
------------
id | table_id (fK) | value
And two models Table and ValueTable . That way (assuming proper eloquent setup) you can just do:
$tableRow = Table::whereHas("value", function ($q) use ($tadaydate) {
return $q->where("value",$tadaydate);
})->get();
You can use whereIn for this. In whereIn you can pass your array like this:
$values_list = [$val1,$val2,$val3];
$data = YourModel::whereIn($tadaydate, $values_list)->get();
You should try this:
$tadaydate=ddate('m/d/Y');
$result = value_table::where('value_1',$tadaydate)
->orWhere('value_2',$tadaydate)
->orWhere('value_3',$tadaydate)
->orWhere('value_4',$tadaydate)
->orWhere('value_5',$tadaydate)
->get();
Updated Answer
$user_list = value_table::where(function($query) use ($tadaydate){
$query->where('value_1', =, $tadaydate);
$query->where('value_2', =, $tadaydate);
$query->where('value_3', =, $tadaydate);
$query->where('value_4', =, $tadaydate);
$query->where('value_5', =, $tadaydate);
})
->get();

laravel whereraw with where in statement

I'm trying to use a WHERE IN statement in the query builder using whereRaw but it doesn't seem to work. I'm not trying to select values from other tables though, just selecting from multiple values.
I've tried these 3 approaches:
return $this->object->whereRaw("`status` = 'active' AND `salesType` IN ( ? ) AND `region_id` = ?", array("'sale','buy'","1"))->paginate(10);
return $this->object->whereRaw("`status` = 'active' AND `salesType` IN ( ? ) AND `region_id` = ?", array("sale,buy","1"))->paginate(10);
return $this->object->whereRaw("`status` = 'active' AND `salesType` IN ( ? ) AND `region_id` = ?", array(array("sale,buy"),"1"))->paginate(10);
Why don't you use where and whereIn` methods?
return $this->object->where('status', '=', $active)->whereIn('salesType', $array);

Resources