PHP Laravel: Concat Like clause within inner join - php

In php laravel i am using mysql / direct query which is shown as below:
$point_rewards = DB::select("select * from integral_history_listing INNER JOIN outlets ON integral_history_listing.branch_c LIKE CONCAT('%', outlets.outlet_code, '%') where outlets.merchant_id LIKE ".Auth::user()->id." ORDER BY integral_history_listing.add_time_c DESC");
I am able to use mysql query to get any related value to the outlet code using like clause... however i wish to write it using php laravel query builder like below :
$notices = DB::table('integral_history_listing')
->join('outlets', 'outlets.outlet_code', 'LIKE', 'integral_history_listing.branch_c')
->where('outlets.merchant_id', 'LIKE', Auth::user()->id)
->orderBy('integral_history_listing.add_time_c', 'desc')
->paginate(10);
I have try include concat within the "outlets.outlet_code" but getting module by zero error. I wish to know the proper way in using concat within inner join php laravel built query.

Try this code:
$notices = DB::table('integral_history_listing')
->join('outlets','integral_history_listing.branch_c' , 'LIKE', DB::RAW('CONCAT("%",outlets.outlet_code,"%")'))
->where('outlets.merchant_id', 'LIKE', Auth::user()->id)
->orderBy('integral_history_listing.add_time_c', 'desc')
->paginate(10);

Related

How to join tables with more than one attribute match?

I am trying to turn my raw sql into laravel query builder and I encounter difficulty on how to join multiple tables using with many attributes match.
In this case, I want to join the table jr_h and jr_d with three attributes match (book,p_seq and staff_code) rather than one (book).
Raw sql:
$sql = "select from_time,to_time,t.staff_code,s.name_t as staff_name,t.book,t.p_code,t.p_seq,p.hrs1,s.img_file,
t.hrs_work,p.sharing_cnt as hrs_work, t.hrs_ot as hrs_ot from jr_d as t
inner join jr_h as p on(t.book=p.book and t.p_seq=p.p_seq and t.staff_code=p.staff_code)
inner join astaff as s on(t.staff_code=s.staff_code) ";
Laravel query builder:
$jr_d = DB::table('jr_d')
->join('jr_h', 'jr_d.book', '=', 'jr_h.book')
->join('astaff', 'jr_d.staff_code', '=', 'astaff.staff_code')
->select('jr_h.*','jr_d.*','astaff.*','astaff.name_t as staff_name')
->where('jr_d.ref_group','=','E')
->get();
and also want to know if there is a way to make the query faster since it has a lot of data in the tables.
Laravel joins with multiple conditions:
$results = DB::table('jr_d')
->select('jr_h.*','jr_d.*','astaff.*','astaff.name_t as staff_name')
->join('jr_h', 'jr_d.book', '=', 'jr_h.book')
->join('jr_h as p', function($query){
$query->on('t.book','=', p.book');
$query->on('t.p_seq','=', 'p.p_seq');
$query->on('t.staff_code', '=', 'p.staff_code');
})
->where('jr_d.ref_group','=','E')
->get();
`
Try this:
// ...
->join('jr_h p', function($join) {
$join->on('t.book', '=', 'p.book');
$join->on('t.p_seq', '=', 'p.p_seq');
// ... more conditions
});
Try this.
$jr_d = DB::table('jr_d')
->join('jr_h', 'jr_d.book', '=', 'jr_h.book')
->join('astaff', 'jr_d.staff_code', '=', 'astaff.staff_code')
->select('*','astaff.name_t as staff_name')
->where('jr_d.ref_group','=','E')
->get();

Laravel 5: Native SQL to Query Builder

I am trying to join 2 tables on Laravel 5 and have to use Query Builder. I have already got the sql for it but i am not able to convert it to Query Builder syntax. SQL is below
SELECT v.id, r.full_name, b.full_name, s.full_name
FROM vehicles v
LEFT JOIN clients r ON v.representive_client_id = r.id
LEFT JOIN clients b ON v.buyer_client_id = b.id
LEFT JOIN clients s ON v.seller_client_id = s.id
and what i tried is
$query_result = DB::table('vehicles')
->selectRaw($query)
->leftJoin('clients', 'vehicles.representive_client_id', '=', 'clients.id')
->leftJoin('clients', 'vehicles.buyer_client_id ', '=', 'clients.id')
->leftJoin('clients', 'vehicles.seller_client_id ', '=', 'clients.id')
->paginate(30);
The problem is i dont know how to use AS caluse for Query Builder as i need to retrive 3 different types of full_name columns from vehicles table.Anybody can help me about how to write it in a proper Query Builder syntax ?. Any help would be appreciated.
You can use aliases with select columns and tables as well as joins, because the Query Builder will know to quote them correctly. So you can do this without any problems:
$query_result = DB::table('vehicles v')
->select('v.id', 'r.full_name as r_name', 'b.full_name as b_name', 's.full_name as s_name')
->leftJoin('clients r', 'vehicles.representive_client_id', '=', 'r.id')
->leftJoin('clients b', 'vehicles.buyer_client_id ', '=', 'b.id')
->leftJoin('clients s', 'vehicles.seller_client_id ', '=', 's.id')
->paginate(30);
Of course, you can use whatever aliases you want for the selected columns. Actually one of the examples in the Query Builder Selects Documentation uses aliases: email as user_email.
To check the SQL query generated by the Query Builder you can use the toSql method. So in your case instead of ->paginate(30) you can have ->toSql(), which will return a string with the SQL generated by the Query Builder, which you can compare to your raw query and see if it matches.

Laravel Eloquent - Select MAX with other columns

I'm trying to select a number of columns along with MAX. The raw query would be something like: SELECT users.id, ..., MAX(ur.rank) AS rank but I cannot figure out how to do it using the query builder supplied by Laravel in Eloquent.
This is my attempt:
$user = User::join('users_ranks AS ur', function($join) {
$join ->on('ur.uid', '=', 'users.id');
})
->where('users.id', '=', 7)
->groupBy('users.id')
->first(['users.id', 'users.username', 'MAX(ur.rank) AS rank']);
I simply cannot figure it out. What I want to achieve is I'm selecting a user where users.id = 7, and I'm wanting to select the MAX rank that's in users_ranks where their users_ranks.uid = users.id.
I was told to avoid sub-queries as when working with large result sets, it can slow things down dramatically.
Can anyone point me in the right direction? Thanks.
I think you should rewrite it like this:
DB::table('users')
->select(['users.id', 'users.username', DB::raw('MAX(ur.rank) AS rank')])
->leftJoin('users_ranks AS ur', 'ur.uid', '=', 'users.id')
->where('users.id', '=', 7)
->groupBy('users.id')
->first();
No sense to use User:: if you use table names later and want to fetch not all of the fields ( 'users.id', 'users.username' ).

Laravel Query Builder - sum() method issue

I'm new to laravel and I have some issues with the query builder.
The query I would like to build is this one:
SELECT SUM(transactions.amount)
FROM transactions
JOIN categories
ON transactions.category_id == categories.id
WHERE categories.kind == "1"
I tried building this but it isn't working and I can't figure out where I am wrong.
$purchases = DB::table('transactions')->sum('transactions.amount')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->select('transactions.amount')
->get();
I would like to get all the transactions that have the attribute "kind" equal to 1 and save it in a variable.
Here's the db structure:
transactions(id, name, amount, category_id)
categories(id, name, kind)
You don't need to use select() or get() when using the aggregate method as sum:
$purchases = DB::table('transactions')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->sum('transactions.amount');
Read more: http://laravel.com/docs/5.0/queries#aggregates
If one needs to select SUM of a column along with a normal selection of other columns, you can sum select that column using DB::raw method:
DB::table('table_name')
->select('column_str_1', 'column_str_2', DB::raw('SUM(column_int_1) AS sum_of_1'))
->get();
You can get some of any column in Laravel query builder/Eloquent as below.
$data=Model::where('user_id','=',$id)->sum('movement');
return $data;
You may add any condition to your record.
Thanks
MyModel::where('user_id', $_some_id)->sum('amount')

running a mysql query containing division in laravel 5

I want to run this mysql query in Laravel 5 using the DB query :
// SELECT *, rating/number as total FROM `courses` order by total DESC;
This is what I tried :
$query = \DB::table('courses')->select('*');
$courses = $query->addSelect('rating/number as total')
->orderBY('total DESC')
->get();
but, rating/number is considered as a table column . The same thing happens when I tried it inside parenthesis (rating/number).
Any help?
$courses = \DB::table('courses')
->selectRaw('*, rating/number as total')
->orderBY('total', 'DESC')
->get();
Can you use Raw Expressions for it? Maybe something like this:
$courses = \DB::table('courses')
->select(DB::raw('*, (rating / number) as total'))
->orderBy('total DESC')
->get();

Categories