Laravel From Raw DB to Eloquent - php

i m trying to change my laravel raw query to eloquent, since now i have got some basics of eloquent and i have tried making blogs in laravel.
But some complexity has remain the same.
First: this is my Raw SQL:
select group_concat(DISTINCT q.sku SEPARATOR ", ") as sku, `sales_flat_order`.`status`, `sales_flat_order`.`increment_id`, `sales_flat_order`.`shipping_description`, `sales_flat_order`.`subtotal`, `sales_flat_order`.`customer_email`, `d`.`country_id`, `d`.`region`, `d`.`city`, `d`.`postcode`, group_concat(DISTINCT q.name SEPARATOR ", ") as name, concat(sales_flat_order.created_at) AS created_at from `sales_flat_order` left join `sales_flat_order_item` as `q` on `sales_flat_order`.`entity_id` = `q`.`order_id` left join `sales_flat_order_address` as `d` on `d`.`parent_id` = `sales_flat_order`.`entity_id` group by `sales_flat_order`.`increment_id` order by `sales_flat_order`.`increment_id` asc
My Raw query in Laravel:
SalesFlatOrder::leftJoin('sales_flat_order_item as q','sales_flat_order.entity_id', '=','q.order_id')
->leftJoin('sales_flat_order_address as d', 'd.parent_id', '=', 'sales_flat_order.entity_id')
->select((array(DB::Raw('group_concat(DISTINCT q.sku SEPARATOR ", ") as sku'),'sales_flat_order.status','sales_flat_order.increment_id', 'sales_flat_order.shipping_description','sales_flat_order.subtotal','sales_flat_order.customer_email','d.country_id', 'd.region', 'd.city','d.postcode',DB::raw('group_concat(DISTINCT q.name SEPARATOR ", ") as name'),DB::raw('concat(sales_flat_order.created_at) AS created_at'))))
->groupBy('sales_flat_order.increment_id')
->orderBy('sales_flat_order.increment_id')
->paginate(10);
Now i am trying to change this whole raw query into eloquent. I have already made models. So following is my eloquent query which is in my controller.
public function detailed(){
$sales = SalesFlatOrder::with('address')->groupBy('increment_id')->orderBy('increment_id')->paginate(10);
return View::make('detailed')->with('sales', $sales);
}
My Problem: 1:
I do have group concat (Distinct q.sku) . So how to do that with eloquent. Because sometimes you need to do group by Date. or group by Orders. So how to show Distinct data so sku column. So how to convert this full fledge raw query into Eloqeunt where we have group_concat, Distinct for so many columns of DB

First create a Custom Collection:
$customCollection = new \Illuminate\Database\Eloquent\Collection;
Then, you can do this like that:
$user =new User;
$user->setRawAttributes((array) $userRawData);
$customCollection->add($user);
Regards!

You can move from RAW to Eloquent elegant queries with models relationship, eloquent DB tables naming convention (without specifying table name in model), route data binding crom DB and scopes.
But still, sometimes you will have to help youself with some RAW for more complicated operations.

Related

How to do order by the eloquent query without using join relationship in laravel?

How to order laravel eloquent query using parent model?
I mean I have an eloquent query where I want to order the query by its parent without using join relationship?
I used whereHas and order by on it, but did not work.
Here is a sample of my code:
$query = Post::whereHas('users')->orderBy('users.created_at')->get();
If you want to order Post by a column in user you have to do a join in some way unless you sort after you retrieve the result so either:
$query = Post::select('posts.*')
->join('users', 'users.id', 'posts.user_id')
->orderBy('users.created_at')->get();
Note that whereHas is not needed anymore because the join (which is an inner join by default) will only result in posts that have a user.
Alternatively you can do:
$query = Post::has('users')
->with('users')
->get()
->sortBy(function ($post) { return $post->users->created_at; });
The reason is that eloquent relationships are queried in a separate query from the one that gets the parent model so you can't use relationship columns during that query.
I have no clue why you wanted to order Posts based on their User's created_at field. Perhaps, a different angle to the problem is needed - like accessing the Post from User instead.
That being said, an orderBy() can accept a closure as parameter which will create a subquery then, you can pair it with whereRaw() to somewhat circumvent Eloquent and QueryBuilder limitation*.
Post::orderBy(function($q) {
return $q->from('users')
->whereRaw('`users`.id = `posts`.id')
->select('created_at');
})
->get();
It should generate the following query:
select *
from `posts`
order by (
select `created_at`
from `users`
where `users`.id = `posts`.id
) asc
A join might serve you better, but there are many ways to build queries.
*As far as I know, the subquery can't be made to be aware of the parent query fields
You can simply orderBy in your Post model.
public function users(){
return $this->belongsTo(User::class, "user_id")->orderByDesc('created_at');
}
I hope this helps you.
You can try
Post::query()
->has('users')
->orderBy(
User::select('created_at')
->whereColumn('id', 'posts.user_id')
->orderBy('created_at')
)
->get();
The sql generated would be like
select * from `posts`
where exists (select * from `users` where `posts`.`user_id` = `users`.`id`)
order by (select `created_at` from `users` where `id` = `posts`.`user_id` order by `created_at` asc) asc
But I guess join would be a simpler approach for this use case.
Laravel Docs - Eloquent - Subquery Ordering

How to select sub-query with left join inside using eloquent?

I'm very new to Laravel, how can I make this query in Laravel using Eloquent model:
SELECT
(
SELECT departments.deptname FROM school.counts
LEFT JOIN reference.departments
ON counts.departmentcode = department.departmentcode
WHERE counts.countid = a.countsid
) AS departmentDesc
FROM school.subjecthdr a
LEFT JOIN school.subjectdtls b
ON a.subjectid = b.subjectid;
I don't wish to use raw queries, is there any way? I still appreciate raw query suggestions if there's any.
I think you still need some raw queries.
$dept_desc = \DB::table('school.counts')
->leftjoin('reference.departments', 'counts.departmentcode', '=', 'departments.departmentcode')
->whereRaw('counts.countid = a.countsid')
->selectRaw('departments.deptname');
\DB::table('school.subjecthdr AS a')
->leftjoin('subjectdtls AS b', 'a.subjectid', '=', 'b.subjectid')
->selectRaw('(' . $dept_desc->toSql() . ') AS departmentDesc')
->get();
PS: I think you leftjoin subjectdtls b but it seems you don't need it.
And you are using not only one database, if you want to use Eloquent\Builder,
you need to do something like this:
How to use multiple databases in Laravel

querybuilder join query in Doctrine2 for Symfony2

Could somebody convert this query for me in querybuilder?
SELECT m.id,n.unitid
FROM mappaths m JOIN unitids n on (m.id=n.id) where n.databaseid=1
I am using this query but it gives me all the values of mm.unitid, while my requirement is to get only one value that is defined by test=1 variable
$query=$qb->select('mm.unitid')
->from('ApiMapBundle:Mappaths','m')
->from('ApiMapBundle:Unitids','mm')
// ->leftJoin('m','u')
->leftJoin('m.refUnitids1','u','WITH','m.id = u')
// ->leftJoin('m.refUnitids2','v')
->where('m.id=:test')
->setParameter('test',1)
->getQuery()->getResult();
Try following:
$query = $qb->select('mm.unitid')
->from('ApiMapBundle:Mappaths','m')
->innerJoin('m.refUnitids1','mm','WITH','m.id = mm.FIELD') //you need to specify on which field of mm join should be done
->where('m.id=:test')
->setParameter('test',1)
->getQuery()
->getResult();
You need to specify field of Unitids which should be used to join to Mappaths. The best way would be to define this relation in Entity definition, then you can use just ->innerJoin('m.refUnitids1','mm') without additional join parameters.
Also, in this case, it is better to use innerJoin instead of leftJoin

SQL exists in Laravel 5 query builder

Good morning,
I've been trying for quite a lot of time to translate this query(which returns an array of stdClass) into query builder so I could get objects back as Eloquent models.
This is how the query looks like untranslated:
$anketa = DB::select( DB::raw("SELECT *
FROM v_anketa a
WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)
Order by redni_broj limit 1"
), array( 'lv_id_user' => $id_user,
));
I have tried this, but it gives a syntax error near the inner from in the subquery:
$anketa = V_anketa::selectRaw("WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)", array('lv_id_user' => $id_user,)
)->orderBy('redni_broj')->take(1)->first();
The problem is this exists and a subquery in it. I couldn't find anything regarding this special case.
Assume each table has an appropriate Eloquent model.
V_anketa is a view. The db is postgresql.
As far as the query goes I believe this should work:
$anketa = V_anketa::whereNotExists(function ($query) use ($id_user) {
$query->select(DB::raw(1))
->from('user_poeni')
->where('anketa.id', '=', 'a.id')
->where('user_id', '=', $id_user);
})
->orderBy('redni_broj')
->first();
but I'm not clear on what do you mean by "assuming every table has an Eloquent model" and "V_anketa" is a view...
Assuming the SQL query is correct, this should work:
$anketa = DB::select(sprintf('SELECT * FROM v_anketa a WHERE NOT EXISTS (SELECT 1 FROM user_poeni WHERE anketa_id = a.id AND user_id = %s) ORDER BY redni_broj LIMIT 1', $id_user));
If you want to get back an Builder instance you need to specify the table:
$anketa = DB::table('')->select('');
If you however, want to get an Eloquent Model instance, for example to use relations, you need to use Eloquent.

Concat_ws in propel

how can I modify my propel query to get the same result as the following MySQL query ?
SELECT v.id,CONCAT_WS(" ",b.name,v.model) AS car_name
FROM vehicle v
JOIN account_vehicle av ON av.account_id=:uid
LEFT JOIN brands b ON b.id=v.manufacturer
WHERE av.vehicle_id=v.id
Right now i have something like that
$query = VehicleQuery::create('v')
->joinAccountVehicle('av')
->leftJoinBrands('b')
->select(array('v.Id', 'b.Name', 'v.Model'))
->where('av.VehicleId=v.Id')
->find();
How can i modify the propel use - to get the same result ? I'm having difficulties with the concat_ws function in propel.
I've tried using the Criteria model - but I cant add the joined table (criteria requires TABLEPEER:COLUMN_NAME's and rejects my aliases)
Try something like this:
$query = VehicleQuery::create('v')
->joinAccountVehicle('av')
->leftJoinBrands('b')
->select(array('v.Id', 'b.Name', 'v.Model','CONCAT_WS(" ",b.name,v.model) AS car_name'))
->where('av.VehicleId=v.Id')
->find();

Categories