Laravel fetch raw query result - laravel

I don't want laravel to format my query result to an array or object ..etc. All I want, is to run the result set from database and then I will manually do the fetch myself in my custom code.
At the moment, I ran my select query and get my result in an array. The reasons for that, because the result is huge and I want to stream it directly to API.
$result = self::$db->select('select * from customer');
How can I tell laravel, to return my query result set without any format at all?

You can use DB:Raw like:
$results = DB::table('users')->select(DB::raw("*"))->get()
Or
$results = DB::select('select * from users where id = ?', [1]);
These two will return a neat object without any casts or relations etc. You can also make any object or array your API need by simple eloquent models by the way. Please explain more about data type you wanna extract from model query.

You must be use ->toSql() or ->dd()
Exapmle
Customer::toSql(); // select * from `customer`
if you want some condition
$query = Customer::where(`some conditions`);
$sql = $query->toSql();
$bindings = $query->getBindings();
$sql = str_replace('?', '%s', $sql);
$sql = sprintf($sql, ...$bindings);

Thanks everyone, I end up writing a raw function to query the data I want from database.
public static function dataStreamJSON($stmt, $headers)
{
return Response::stream(function() use ($stmt){
$conn = self::getConnection();
$result = sqlsrv_query($conn, "exec $stmt");
echo '
{
"Customers": {
"Customer": [';
$counter = 0;
while($customer = sqlsrv_fetch_object($result)) {
if($counter !== 0){
echo ",";
}
$counter++;
$row = [
'Firstname' => $customer->Firstname,
'Lastname' => $customer->Lastname,
...
];
echo json_encode($row);
unset($row);
unset($customer);
}
echo ']
}
}';
#sqlsrv_free_stmt($result);
#sqlsrv_close($conn);
}, 200, $headers);
}
The purpose of this code is to stream the data out to JSON format on browser without store the data in any variable, which will caused “out of memory” error.
I managed to stream 700MB of JSON data to the browser without any error. With this code, you will never run into “out of memory” error.
Best way to test this, is to use CURL to access your API and download the data to a JSON file. If you open on browser, it will freeze your screen because browser can't handle large data.

You can use toArray() or toJson() methods like below:
$array = Customer::all()->toArray();
$json = Customer::all()->toJson();
echo '<pre>';
print_r($array);
print_r($json);
If you want to run raw SQL Queries, you can do as below
$users = DB::select('select * from users where 1');
echo '<pre>';
print_r($users);

You can use
1) query builder way:-
DB::table('your_table_name)->select('your_col_names')->get();
eg:- DB::table('shop')->select('product_id','product_name')->get();
2) use laravel Raw
$orders = DB::table('orders')->selectRaw('price * ? as price_with_tax', [1.0825])->get();
3) for select raw
$product_count = DB::table('product')->select(DB::raw('count(*) as total_product_count'))->where('status',1)->get();

Related

Laravel - How to convert Stdclass object to Array

I'm facing this problem when use database in Laravel. How can i convert that to Array the most simpletest?
$data = DB::table('users')->get();
Please try this. this will return array of objects.
$result = json_decode(json_encode($data, true));
*Updated
if you want to convert all nested properties to the array, try this.
$result = json_decode(json_encode($data, true), true);
get() will return a collection. If you want to get an array of objects, use the toArray() method:
$data->toArray();
If you want to convert every object to an array too, do this:
$data->map(function($i) {
return (array)$i;
})->toArray();
I usually run into this problem when I use DB::select and manually write my sql:
$sql = 'SELECT *
FROM ba_pics ba
INNER JOIN pages pgs
ON ba.service_page_id = pgs.id';
$baPics = DB::select($sql);
$baPics = json_decode(json_encode($baPics, true), true);
return view('beforeAndAfter',['baPics'=>$baPics, 'lodata'=>'no lodata yet']);
Here is another way using PHP's array_map function:
$sql = 'SELECT *
FROM ba_pics ba
INNER JOIN pages pgs
ON ba.service_page_id = pgs.id';
$baPics = DB::select($sql);
$baPics = array_map(function($i) {
return (array)$i;
}, $baPics);
return view('beforeAndAfter',['baPics'=>$baPics, 'lodata'=>'no lodata yet']);

Is there a way to display the value instead of (?) using query builder in laravel eloquent?

I'm using Eloquent Query Builder to produce raw sql for me. My goal is to return a sql query like this
select * from accounts where id = '120'
now i tried
$query = \App\Account::query();
$query = $query->where('id', 120);
dd($query->toSql());
Output:
select * from `accounts` where `id` = ?
is there a way to display the value instead of (?) because this is not a valid query on the third party API that i'm using.
I'm expecting to produce a query on my first example that i give.
Note: I'm not querying on my database, i will use that raw query to pass on the 3rd party API. All i want is to produce only a raw sql. Any suggestion would be appreciated. Thanks!
Yes, you can print the parameters value by using getBindings()
print_r( $query->getBindings() );
Array
(
[0] => instructor
[1] => 1
)
Found a solution for this, maybe it can help to someone that has same problem with me.
You can check this link: https://gist.github.com/JesseObrien/7418983
public function getSql()
{
$builder = $this->getBuilder();
$sql = $builder->toSql();
foreach($builder->getBindings() as $binding)
{
$value = is_numeric($binding) ? $binding : "'".$binding."'";
$sql = preg_replace('/\?/', $value, $sql, 1);
}
return $sql;
}

Laravel use DB::table instead of ::find() to save or modify records

In my project I need to find some data from sql without using id in table. For example we can use this code to find data by id:
$result = BuyCard::find(10);
but I want to search in other table column such as user_code without changing laravel stucture instead if id with other column. I've tried this:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
$data->result_transaction = 1;
$data->save();
For this code I'm getting an error but I can use it. But this code works fine:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
$data = BuyCard::find($data->id);
$data->result_transaction = 1;
$data->save();
how to edit this without using
$data = BuyCard::find($data->id);
between code? code is working fine but this is not correct.
Try to change this:
$data = DB::table('buy_card_transactions')->where('transaction_id', $key)->first();
To:
$data = DB::table('buy_card_transactions')->where(array('transaction_id' => $key))->first();
Or:
BuyCard::where('transaction_id',$key)->first();

Laravel Eloquent query with optional parameters

I am trying to learn whether or not there is a simple way to pass a variable number of parameters to a query in Eloquent, hopefully using an array.
From what I can find, there doesn't seem to be a way to do this without looping through the Input to see what was set in the request.
Examples here: Laravel Eloquent search two optional fields
This would work, but feels non-Laravel to me in its complexity/inelegance.
Here is where I am, and this may not be possible, just hoping someone else has solved a similar issue:
$where = array("user_id" => 123, "status" => 0, "something else" => "some value");
$orders = Order::where($where)->get()->toArray();
return Response::json(array(
'orders' => $orders
),
200
);
That returns an error of course strtolower() expects parameter 1 to be string, array given.
Is this possible?
Order::where actually returns an instance of query builder, so this is probably easier than you thought. If you just want to grab that instance of query builder and "build" your query one where() at a time you can get it like this:
$qb = (new Order)->newQuery();
foreach ($searchParams as $k => $v) {
$qb->where($k, $v);
}
return $qb->get(); // <-- fetch your results
If you ever want to see what query builder is doing you can also execute that get() and shortly after:
dd(\DB::getQueryLog());
That will show you what the resulting query looks like; this can be very useful when playing with Eloquent.
You can try this:
Method 1:
If you have one optional search parameter received in input
$orders = Order::select('order_id','order_value',...other columns);
if($request->has(user_id)) {
$orders->where('orders.user_id','=',$request->user_id);
}
//considering something_else as a substring that needs to be searched in orders table
if($request->has('something_else')) {
$orders->where('orders.column_name', 'LIKE', '%'.$request->something_else.'%');
}
$orders->paginate(10);
Method 2:
If you have multiple optional parameters in input
$orders = Order::select('columns');
foreach($input_parameters as $key => $value) {
//this will return results for column_name=value
$orders->where($key, $value);//key should be same as the column_name
//if you need to make some comparison
$orders->where($key, '>=', $value);//key should be same as the column_name
}
return $orders->paginate(15);

Codeigniter: does $this->db->last_query(); execute a query?

Does query execution happen at the get_where() clause of the following codeigniter active record statement?
$this->db->select('*');
$q = $this->db->get_where('Contacts', array('id' => $contact_id));
$sql = $this->db->last_query();
Or does it happens once you call the result_array()?
And is $this->db->last_query(); a reliable way in getting the query string.
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this.
Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!!
Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Take a look at this example
For me save_queries option was turned off so,
$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;
Ref: Can't get result from $this->db->last_query(); codeigniter
For Me It Works Perfectly: Source Disclosure : This Source website Belongs to me , i am also sharing solutions on my website ...
public function index()
{
$db = \Config\Database::connect();
$heroesCount = $db->table('products')->countAll();
echo $db->getLastQuery();
exit;
}

Resources