Query eloquent in Laravel 5.8 - php

I have a problem with a query that I am doing in Laravel 5.8 using Eloquent, that I really don't know what happens.
I will explain:
My Eloquent query is this:
$naviones=DB::connection('naviones')->table('ps_customer')
->select('ps_orders.id_order','ps_customer.firstname','ps_customer.lastname','ps_customer.email','ps_address.address1',
'ps_address.postcode','ps_address.city','ps_address.phone_mobile','ps_orders.id_order','ps_orders.reference',
'ps_order_detail.product_name','ps_order_detail.product_quantity','ps_shop.name as tienda','ps_carrier.name as transportista')
->join('ps_address','ps_customer.id_customer','=','ps_address.id_customer')
->join('ps_orders', function($join){
$join->on('ps_address.id_customer','=','ps_orders.id_customer')
->where('ps_address.id_address','=','ps_orders.id_address_delivery');
})
->join('ps_order_detail','ps_orders.id_order','=','ps_order_detail.id_order')
->join('ps_shop','ps_order_detail.id_shop','=','ps_shop.id_shop')
->join('ps_carrier','ps_orders.id_carrier','=','ps_carrier.id_carrier')
->where('ps_orders.id_order','=',11389)
->get();
As you can see, I am making this query to a database, which is not necessarily the one used by the application. That eloquent query translates to this:
SELECT
`ps_orders`.`id_order`,
`ps_customer`.`firstname`,
`ps_customer`.`lastname`,
`ps_customer`.`email`,
`ps_address`.`address1`,
`ps_address`.`postcode`,
`ps_address`.`city`,
`ps_address`.`phone_mobile`,
`ps_orders`.`id_order`,
`ps_orders`.`reference`,
`ps_order_detail`.`product_name`,
`ps_order_detail`.`product_quantity`,
`ps_shop`.`name` AS `tienda`,
`ps_carrier`.`name` AS `transportista`
FROM
`ps_customer`
INNER JOIN `ps_address` ON `ps_customer`.`id_customer` =
`ps_address`.`id_customer`
INNER JOIN `ps_orders` ON `ps_address`.`id_customer` =
`ps_orders`.`id_customer`
AND `ps_address`.`id_address` = ps_orders.id_address_delivery
INNER JOIN `ps_order_detail` ON `ps_orders`.`id_order` =
`ps_order_detail`.`id_order`
INNER JOIN `ps_shop` ON `ps_order_detail`.`id_shop` =
`ps_shop`.`id_shop`
INNER JOIN `ps_carrier` ON `ps_orders`.`id_carrier` =
`ps_carrier`.`id_carrier`
WHERE
`ps_orders`.`id_order` = 11389
Well, the point is that if I take that query and execute it in Mysql, it gives me the information that I am requiring, but, in eloquent the collection, it is empty. That is what drives me crazy that the collection is empty. That query is being delivered to me by eloquent, how am I ensuring that it is delivered by eloquent? I generated an error on purpose in one of the fields for Laravel to inform me and show me the complete query to examine it and that is the query:
At the end of the red circle I show the error created on purpose to see the complete query and see if it is well armed.
I do not understand what is happening, I do not know what to do, I have two days and I have no idea of ​​what is happening.
I hope you can give me some idea, thanks.

If you remove this:
->join('ps_orders', function($join){
$join->on('ps_address.id_customer','=','ps_orders.id_customer')
->where('ps_address.id_address','=','ps_orders.id_address_delivery');
})
is there any result? maybe the problim in this function.
also, can you change this:
DB::connection('naviones')->table('ps_customer')
to
DB::table('ps_customer')

Related

How to convert given SQL query to Eloquent laravel?

I am bit struggling to convert below given SQL query to eloquent.
Here is an example of what I am trying to do -
SELECT u.wallet_address AS wallet_address, p.id AS project_id
FROM users u, projects p, investment_investor i
WHERE u.id = i.user_id AND
p.id=i.project_id AND
u.wallet_address <> '' AND
p.wallet_address <> '' AND
p.contract_address <> ''
GROUP BY u.id, p.id;
The below SQL query gives me the expected output, which I am able to build with the Laravel DB query builder. But want to standardise it to Laravel framework.
Your help is much appreciated!
First thing you need to have to be able to write queries in the laravel way is something called Model. Example of a model would be like so
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
//
}
You can read more about it here
Once you create it, you can start writing queries. For example
$results = Users::selectRaw('users.wallet_address as `wallet_address`,'.
'id as `project_id`')
->get();
You can read more about joins and other things here
$result=DB::table('investment_investor')
->select('users.wallet_address as wallet_address','projects.id AS project_id')
->join('users','users.id','=','investment_investor.user_id')
->join('projects','projects.id','=','investment_investor.project_id')
->where('users.wallet_address','!=','')
->where('projects.wallet_address','!=','')
->where('projects.contract_address','!=,'')
->groupBy('users.id', 'projects.id')
->get();

laravel 5.4 how to write select from multi table query

How am using laravel 5.4,
to write sql query to get data from multiple tables for below query
select l.party_id,l.container_id,p.party_name from
`tbl_container_lease` l, `tbl_partys` p
where l.`party_id` = p.`id` and l.`user_id` = 5
Now am using this
Containerlease::whereHas('getpartys',function($q){})
->where('user_id','=',$user_id)
->get();
but it is getting too confuse to use
is there any better alternative to use this query by using model..
You would have to join the tables to do this.
Containerlease::join('tbl_partys', 'tbl_partys.id', '=', 'tbl_container_lease.party_id')
->where('tbl_container_lease.user_id', 5)
->select('tbl_partys.*', 'tbl_container_lease.*');
->get();
However, an even better way would be to create relations if you are using Eloquent. The documentation for this can be found here: https://laravel.com/docs/5.4/eloquent-relationships
It would be better, since you're in laravel after all, to make use of laravel relationships.
Make sure you have a party model:
php artisan make:model Party
Assuming one lease has one party, In your container lease model add:
public function party(){
return $this->hasOne('App\Party', 'id', 'party_id');
}
Then access your model
ContainerLease::with('party')->where('user_id', '=', 5)->get();

How to count items join it and paginate?

I'm trying to count some items from the table and join it with the another table so I use the following code
Article::join("article_comments", "article_comments.article_id", "=","articles.id")->
select(["articles.title", "articles.content", "articles.created_at", DB::raw('count(article_comments.id) as commentsCount')])->paginate(10) ;
But I always get only first item
Shouldn't there be a group by if you use aggregates?
Something like:
Article::join("article_comments", "article_comments.article_id", "=","articles.id")->
select(["articles.title", "articles.content", "articles.created_at", DB::raw('count(article_comments.id) as commentsCount')])->
groupBy('articles.id')->
paginate(10);
Also since you're no using your joined table for filtering you might wanna consider eager loading. However in your case you only get articles with comments. When using eager loading you'd get all articles (including the ones without comments).
Something like that should work:
Article::with([
'comments' => function ($query) {
$query
->select('article_id', DB::raw('COUNT(`id`) AS `commentCount`'))
->groupBy('article_id')
}
])
->paginate(10);
Now you should be able to access the count like this:
echo $article->comments->first()->commentCount;
Did not test the solution. You might wanna check if $article->comments->first() exists.
Or if you wanna expand your model a little here are some even better thoughts

How to run a query in Laravel 4 using eloquent

I have read the documentation but I can't quite figure out how to run the following query in Laravel 4
SELECT
COUNT(*)
FROM
acl a,
routes r
WHERE
(a.user_id = 1 OR
a.group_id IN(SELECT group_id FROM user_group_junction WHERE user_id = 1)) AND
r.route = 'protected' AND
a.routes_id = r.id;
So how would I run the query in Laravel 4 using eloquent?
Yes each table has a model and relationships are defined
Based on my selected answer the following is what I came up with (And works)
Acls::join('routes','routes.id','=','acl.routes_id')
->where('routes.route','=','protected')
->Where(function($in_parenthesis) use($user_id){
$in_parenthesis->whereIn('acl.group_id',function($where_in) use($user_id){
$where_in->select('group_id')
->from('user_group_junction')
->where('user_id','=',$user_id);
})
->orWhere('acl.user_id','=',$user_id);
})
->count();
Methods called on Eloquent models pass through to the Illuminate\Database\Eloquent\Builder class, which itself extends from the Illuminate\Database\Query\Builder class. This means that all the things you can do with the query builder, you can also do with Eloquent models. The exception being that you don't need to define the table.
So for example if you wanted to perform a join and a where like you've done above, you would just do:
$query = Acl::join('routes', 'acl.routes_id', '=', 'routes.id')
->where('routes.route', '=', 'protected');
$results = $query->get();
Obviously this isn't your whole query, but you can figure out the rest.

Symfony2 - Custom Query in Entity Repo doesn't seem to return expected results

So I came to a point where I needed to create a custom query in my Entity Repository to do a sub-select.
The query itself seems sound and does indeed find the result I am after (I checked by running the query in Navicat) however, when trying to view the results (using Twig templates) I am getting the following error:
Item "id" for "Array" does not exist in DEMODemoBundle:Staff/Company:company.html.twig at line 42
Line 42 in that template is:
<td>{{ entity.id }}</td>
Previously, I was using a basic "findAll" query in my controller, and the Twig template worked fine (it uses a for loop to go through the results and print out a table)
So, I was under the assumption that if my custom query fetched a list of results, with all the same columns (just 1 added extra in the sub-select, not the ID mentioned though) then everything should be fine!
But clearly not. It seems as though there is another Array level for some reason and I am unsure as to why?
Here is my custom query in the repo (it does a sub select to create a parent_name column):
public function getCompanyWithParent()
{
$dql = 'SELECT c, (SELECT p.name FROM DEMO\DemoBundle\Entity\User\Company p WHERE p.id = c.parent) as parent_name FROM DEMO\DemoBundle\Entity\User\Company c';
$query = $this->getEntityManager()->createQuery($dql);
return $query->getArrayResult();
}
I have tried both:
return $query->getArrayResult();
and
return $query->getResult();
But to no avail.
Any ideas folks?
Sorted it. Seems I had to specify the columns I wanted to pull through e.g. SELECT c.id, c.name ..., and sadly couldn't just use SELECT c, ... FROM ...

Categories