Where Is My Raw Query? - laravel

Here is my controller code;
$temp_table_data = $temp_table
->setTempTable($generated_temp_table)
->newQuery()
->with(['payment' => function ($query) use ($column_values) {
$query->select($column_values);
}])->get();
My toSql query is right below it;
$sql = str_replace(['%', '?'], ['%%', "'%s'"], $temp_table->toSql());
$fullSql = vsprintf($sql, $temp_table->getBindings());
print_r($fullSql);
My code prints out;
select * from `selected_postcodes_1434968225_1`
Where are the details of the payments information that I am "with"ing? If I want to print out the raw query now, to show another developer, to get some help, what am I supposed to do here?

The eager loaded relationships are fetched in a separate query. You can use DB::getQueryLog() to get all run queries. Note that you have to enable it first using with DB::enableQueryLog().
Another alternative is the Laravel Debugbar package that shows you all queries and much more.

Related

How can i convert this sql query in a eloquent laravel command?

in sql query this commando do exactly i wanted:
SELECT
v.id,
(
SELECT sv.status_id
FROM status_viagem sv
WHERE sv.viagem_id = v.id
ORDER BY sv.created_at DESC LIMIT 1 ) AS status_id
FROM viagens v
Here is the sql results:
But i have no idea how can i do this using Laravel eloquent
Basically, a viagem entry can has a lot of status, but i need to get each viagem and their last status entry from status_viagem table (the pivot table)
by the way viagem/viagens means travel.
My class mapping:
class Viagem extends Model
{
...
public function status()
{
return $this->belongsToMany('App\Status')->withTimestamps();
}
...
}
class Status extends Model
{
public function viagens()
{
return $this->belongsToMany('App\Viagem')->withTimestamps();
}
}
The belongsToMany at both classes gets me a many-to-many:
can someone help me? thanks
---------- Temporary Solution -------
Thanks for all help guys. In fact i can't find a nice solution using only eloquent.
Step 1/3 - To bypass this situation i first execute the above sql to grab only the viagens under the desired status_id (last status_viagem entry):
$viagens_ids = DB::select(
"SELECT viagem_id FROM (
SELECT
v.id AS viagem_id,
(
SELECT sv.status_id
FROM status_viagem sv
WHERE sv.viagem_id = v.id
ORDER BY sv.id DESC LIMIT 1 ) AS status_id
FROM viagens v
) AS tt
WHERE tt.status_id = {$status->id}"
);
Step 2/3 - then i used the array_map to organize my viagens ids
$a = array_map(
function($obj) { return $obj->viagem_id; },
$viagens_ids
);
Step 3/3 - And at last i used elequent whereIn to fetch my viagens:
Viagem::with( 'status')->whereIn('id', $a)->get();
In fact i have solved the problem by a-old-sashion-way but i not happy with it because i wish i learn how to do it using eloquent. what bad to me.
There are many ways to query in laravel. I have created a test project for you to try. The gist are:
1. Eloquent ORM
Eloquent ORM is Laravel's magic which have some limitations in eager loading - which i just come across while contemplating your question for hours. It wont play nicely with first(), last(), and some more functions in the constrained eager loading closure.
In your case, our almost there can be fixed:
App\Models\Viagem::with(['status' => function($query){
return $query->orderBy('pivot_created_at', 'desc');
}])
->get()
It will return entire field for Viagem and Status including its pivot table (the status_viagem).
However, if you wanted to retrieve only viagem.id and status_viagem.status_id, you can map() it as such:
App\Models\Viagem::with(['status' => function($query){
return $query->orderBy('pivot_created_at', 'desc');
}])
->get()
->map(function($data){
$o = new stdClass();
$o->id = $data->id;
$o->status_id = $data->status->first()->id;
return $o;
});
Please take note that the statement above require sql query to be ran twice. Eager loading basically works by querying all the Viagem first then queries the Status and map them in memory based on the foreign keys. You can observe that replacing get with toSql will only give you the first query. Please enable Query Logging to see the second query.
2. Query Builder
Embarking from Ryan Adhitama Putra answer, you could do something like:
App\Models\Viagem::join('status_viagem', 'viagens.id', '=', 'status_viagem.viagem_id')
->orderBy('status_viagem.created_at', 'desc')
->groupBy(['status_viagem.status_id', 'viagens.id'])
->select(['viagens.id', 'status_viagem.status_id'])
->get();
This query builder approach guaranteed to be ran only once, you can replace the get() with toSql() to see the resulting query.
3. Raw Queries
Throwing DB::raw() can help sometime, but i really did not want to mention it.
I am not sure what viagens and viagem represent, but I think one of the relationships has to be belongsToMany() and the other hasMany().
then after you set relationships correctly, you can use Eloquent like this :
$status_id = Viagem::with('status')->orderBy('created_at', 'desc')->first()->pluck('status_id');
Try this.
$status_id = Viagem::join('status','viagem.id','status_viagem.viagem_id')
->select('viagem.id','status_viagem.status_id')
->get();

why when i select all data is showing but when i use find or where data not showing even if i check with dd

some make me confusing in laravel when i use all() data is showing but when i select find or where data not showing when i use dd function in laravel
//$regency = Regency::find(1101);
//$regency = Regency::where('number','=',$prov_id);
$regency = DB::table('regencies')->where('province_id', $prov_id);
dd($regency);
i try use eloquent and query builder but still same result.
those is result in dd if i using query builder, but why when i use select all data is showing
What you are showing is the Query Builder you need to execute it with ->get() to get the Collection.
You have to get the data from the query builder in order to receive the results as a collection of objects
// $regency = Regency::findOrFail(1101);
// $regency = Regency::where('number', $prov_id)->get();
$regency = DB::table('regencies')->where('province_id', $prov_id)->get();
dd($regency);
Writing a query builder just produces the SQL query but doesn't actually execute/run it
Hope this helps

when to use get() in query laravel 5

I have a basic query set up in the show method of a laravel resource
public function show($id){
$results = Student::find($id);
$drives= Drive:: where('student_id', $id);
}
The query for $results works perfectly. The query for $drives does not work unless I do ->get() at the end of it. Why is this? what's the difference between the two queries so that one requires the ->get() and the other does not? Solving this problem took me like 5 hrs and i'm just curious as to the functionality behind it so i can avoid this headache in the future.
Some eloquent expressions have a get implicitly. Those ones who are made by a Query Builder will need a ->get() call, find(), findOne()... won't need a get().
https://laravel.com/docs/5.6/eloquent#retrieving-models
https://laravel.com/docs/5.6/queries
use get to execute a builder query. unless you run the get() query wont be executed. get will return a collection.
1 - Use query builder to build queries however you want.
$drives= Drive:: where('student_id', $id);
dd($drives); // will return a query builder, you can use it to build query by chaining
2 - when you are ready to execute the query call get()
$drives= Drive:: where('student_id', $id);
$result = $drives->get()
dd($result); // will return a database query result set as a collection object
If you want to get a single object by id use find, to get a single object
$results = Student::find($id);
dd($result); will return a single model
Using the function find() on a model gets a query result based on the primary key of the model, id in this case.
When using where(), it gets a collection (an object of all query results), so if you only want the first result you must call $drives=Drive::where('student_id', $id)->first();
Here is a more in-depth explanation: the difference of find and get in Eloquent

How can I write this query using the laravel query builder?

I'm on laravel 5.1 using postgres as the DB. I have a fiddle here in case it helps understand my issue: https://www.db-fiddle.com/f/5ELU6xinJrXiQJ6u6VH5/4
with properties as (
select
properties.*,
json_agg(property_fields.*) as property_fields
from
properties
left join fields as property_fields
on property_fields.parent = 'property' and property_fields.parent_id = properties.id
group by properties.id, properties.deal_id, properties.address
)
select
deals.*,
json_agg(properties.*) as deal_properties,
json_agg(deal_fields.*) as deal_fields
from deals
left join properties on deals.id = properties.deal_id
left join fields deal_fields on deal_fields.parent = 'deal' and deal_fields.parent_id = deals.id
group by deals.id, deals.name
order by deals.id
Writing most of this is fairly straight forward. The problem I'm having is with the with properties as (...) block. I've tried something like:
DB::statement('WITH properties AS ( ... )')
->table('deals')
->select(' deals.*, json_agg(properties.*) as deal_properties, ')
...
->get();
But I notice the execution stop after DB::statement()
Is there a method in the Query Builder that I'm missing? How can I prefix my query with the WITH properties AS (...) statement?
I think it should also be noted that I'm trying to implement a Repository Pattern and I can't just wrap a DB::statement() around the whole query.
I've created a package for common table expressions: https://github.com/staudenmeir/laravel-cte
$query = 'select properties.*, [...]';
DB::table('deals')
->withExpression('properties', $query)
->leftJoin([...])
->[...]
You can also provide a query builder instance:
$query = DB::table('properties')
->select('properties.*', [...])
->leftJoin([...])
->[...]
DB::table('deals')
->withExpression('properties', $query)
->leftJoin([...])
->[...]
if you want some data fetch from a table you can use this type of code
$user = DB::table('table name')->where('name', 'John')->where('height','!>',"7")->select('table fields which you want to fetch')->get();
Or try using the larevel Eloquent ORM which will make things easier with the database.
for more example or reference
https://laravel.com/docs/5.0/queries
I think you can actually do this with eager loading,
assuming that the relationships are set up correctly.
(More reading here: https://laravel.com/docs/5.4/eloquent-relationships#constraining-eager-loads)
So I think you'd be able to add something like
->with(['properties' => function ($query) {
$query->select('field')
->leftJoin('join statement')
->groupBy('field1', 'field2');
}])

Eager load single item with Eloquent belongsToMany

I have a Batch model, which hasMany Results and belongsTo a Project. The current status of a batch is based on the status of its most recent Result. So, in my batch model I have this:
public function allForProject($pid)
{
$batches = $this
->with(static::$relatedObjects)
->with('current_status')
->where('project_id', '=', $pid)
->get();
return $batches;
}
public function current_status()
{
return $this
->belongsToMany('BehatEditor\Models\Result')
->orderBy('created_at', 'DESC')
->limit(1)
;
}
...So by saying "->with('current_status')" I am trying to eager load only the most recent result for that batch - there may be thousands of them per batch that I do not want to return to the front end.
Now, this doesn't break, but the "limit(1)" actually seems to limit the number of Batches that get returned with a Result. Even though each one of my Batches has 2 results with my test data, when I use limit(1) only one of them comes back with any data. When I use limit(2), only 2 batches come back with a single current_status record (desired) but the rest have an empty array for current_status.
This is a Silex project using Eloquent as an ORM, so Laravel specific methods won't work.
Any help is much appreciated!
UPDATE:
It looks like Eloquent just doesn't support this. see http://irclogs.julien-c.fr/2013-12-19/01:48#log-52b25061a599aafb54008650. I would like to update my question to be how can I cleanly add the raw SQL I need to my query? Can I supply my own method that holds only the SQL needed, or do I need to replace all ORM usage in allForProject()?
Instead of ->limit(1), use ->first().
Update: Misread what you said, this should work.

Resources