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
Related
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
I need to join two table to fetch data with multiple condition on leftjoin but
i am getting this error. Not enough arguments for the on clause I am using laravel5.2. How to use raw query with leftjoin multiple condition.
$activityDetail = DB::table('table1 as UA')
->selectRaw('SUM(UA.total_calory) as total_calory,
SUM(UA.flight_descend) as flight_descend,date('.$tz_start_date.') as start_date')
->leftjoin('table2 as LC',function($join) use($tz_lccreated_date,$dateRange){
$join->on('LC.user_id_fk','=','UA.user_id_fk');
$join->on('LC.is_active','=',DB::raw('1'));
$join->on(' date('.DB::raw($tz_lccreated_date).') '.DB::raw($dateRange));
})
->whereRaw(' date('.$tz_start_date.') '.$dateRange)
->where('UA.user_id_fk','=',base64_decode($params['uid']))
->groupBy(DB::raw('date('.$tz_start_date.')'))
->get();
Raw query is
select SUM(UA.total_calory) as total_calory,
SUM(UA.flight_descend) as flight_descend,
date(CONVERT_TZ(UA.start_date,"+00:00","+05:30")) as start_date
from `table1` as `UA`
left join `table2` as `LC`
on `LC`.`user_id_fk` = `UA`.`user_id_fk` and `LC`.`is_active` = 1
and `date(CONVERT_TZ(LC`.`created_date,"+00:00","+05:30"))` = `current_date`
where date(CONVERT_TZ(UA.start_date,"+00:00","+05:30")) = current_date
and `UA`.`user_id_fk` = 411
group by date(CONVERT_TZ(UA.start_date,"+00:00","+05:30"))
I have resolved my problem, after a lots of analysis, i am not getting any kind of solution of raw query in join clause then i am using subquery and resolve my problem.
$mannualLoggedQuery = 'IFNULL((select sum(calory) as cal from table2 as LC where LC.user_id_fk = "'.base64_decode($params['uid']).'" and date('.$tz_lccreated_date.')'.$dateRange.'),0)';
$activityDetail = DB::table('table1 as UA')->selectRaw('SUM(UA.total_calory) + '.$mannualLoggedQuery.' as total_calory,
date('.$tz_start_date.') as start_date')
->where('UA.user_id_fk','=',base64_decode($params['uid']))
->whereRaw('date('.$tz_start_date.') '.$dateRange)
->groupBy(DB::raw('date('.$tz_start_date.')'))
->get();
What is a diference beetween JoinWith, and useTablenameQuery ? How its work in propel, why JoinWith is faster than useTable_nameQuery ? How work formatter ? Thanks for help :
)
Main difference is when you have filter specifically for the on the right like TableB=?
joinWith: Default Join condition as defined in the schema
$rows = TableAQuery::create()
->joinWith('TableB')
->find();
useTableBQuery Use a filter for the table right
$rows = TableAQuery::create()
->useTableBQuery()
->filterByColumnName($value) // A column in TableB
->endUse()
->filterByColumnName($value2) // A column in TableA
->find();
Notice the second ->filterByColumnA() is outside the ->useTablBQuery, to illustrate that you can have filter on both tables
I'm working with L5 and elequent
My table structure is..
users
id
other field
auctions
id
other field
lots
id
auction_id
other field
lot_user
lot_id
user_id
I want to find auctions for a user.
How can i do this?
$user = User::find($id);
$auctions = $user->auctions();
I have got an idea to do this with eloquent..
$auctions = $user->lots()
->join('auctions','auctions.id','=','lots.id')
->select(['auctions.*'])
->get();
I'm not sure Eloquent is going to be very efficient here, but you could do something like :
In your User(s) class, you need to define a many-many relationship like :
public function lots()
{
return $this->belongsToMany('App\Lot');
}
In your Lot(s) class, you need to define the inverse of a one-to-many relationship like:
public function auctions()
{
return $this->belongsTo('App\Auction')
}
Then, to get Lots for a user, you'd do something like :
$user->lots();
To get auctions, you'd need to loop over lots and call $lot->auctions() for each one, and then filter by id to get the unique auctions.
This is a case where it would probably be easier to use the DB facade to built a query instead of just trying to use Eloquent.
About DB facade.
Raw query will looks like this:
SELECT * FROM auctions AS a
INNER JOIN lots AS l ON (l.auction_id = a.id)
INNER JOIN lot_user AS lu ON (lu.lot_id = l.id AND lu.user_id = $findUserId)
GROUP BY a.id
And using query-builder you can do it like this:
DB::table('auctions')
->join('lots', 'lots.auction_id', '=', 'auctions.id')
->join('lot_user', function ($join) {
$join->on('lot_user.lot_id', '=', 'lots.id')
->where('lot_user.user_id', '=', $findUserId);
})
->groupBy('auctions.id')
->get();
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.