laravel join fake table - laravel

I'm using datatables with server side processing in a Laravel project. My status column is integer, which is then formatted
->editColumn('status', function($orders) use ($statuses) {
return $statuses[$orders->status];
})
But this approach prevents status column from being used in search.
Is sthere a way to join query with fake table? Smth like this
->join('fake_status_table', 'production_orders.status', '=', 'fake_status_table.id')
Drafting two solutions
Solution #1
$orders= DB::table('production_orders')
->select(DB::raw("DECODE (status_id, 1, 'No started',
2, 'Running',
3, 'Done',
4, 'Defect')"))
solution #2
//create tamporary table
$status_table = DB::insert( DB::raw( "CREATE TEMPORARY TABLE statuses") );
$orders = \DB::table('production_requests')
// join it with drawing table
->join('statuses', 'production_requests.status', '=', 'statuses.id')
// Generate result
$result = Datatables::of($orders)->make(true);
// KILL TEMPORARY TABLE
$dropTable = DB::unprepared( DB::raw( "DROP TEMPORARY TABLE statuses" ) );
// RETURN RESULT
return $result;

Views is nothing but a temporary table..
But it was copy of the table itself.. You shall create a view according to your need.. If you want to have the view of your entire table .. then
CREATE VIEW test.v AS SELECT * FROM t;
Or even
CREATE VIEW v AS SELECT qty, price, qty*price AS value FROM t;
Then you shall return some data from the controller and construct the coloumn as we do usual in the datatables
Like this
Jquery :
$(document).ready(function() {
$('#example').DataTable();
} );
And then foreach for the table !!
Hope this helps you

Related

Laravel query builder select all except specific column

I have 2 tables with the same columns except the second table have one more column, this column is foreign key of the first;
what i want is to make union query;but for union the column must the same; so i want to select all column except for the column distinct;
The easy way is to provide in select all the same column:
$a = Table1::select(['column1', 'column2', 'etc...']);
$b = Table2::select(['column1', 'column2', 'etc...']);
and go with $a->union($b)->get();
but if i have too much column, i end up with so much column to provide in the select function; so what i want is to provide in the query the column that i don't want to retrieve;
i can put protected $hidden in the second table model but for some reason i need this distinct column on some other query;
Get all columns name by Schema::getColumnListing($table);
And computes the intersection of arrays
array_intersect($columnsName1, $columnsName2);
I haven't done it with 2 tables but I am using collections and rejecting certain columns on a similar project:-
$row = Table1::firstOrFail();
$exclude=['column_1', 'column_2'];
return collect(array_keys($row->getAttributes()))
->reject(function ($name) use ($row, $exclude) {
return in_array($name, $row->getHidden())
|| in_array($name, $exclude);
}
);

How to count for a substring over two tables in codeigniter

I have two tables
table1
id|name|next_field
table2
id|id_of_table1|whatelse
I do a msql query to get all entries of table1 and the number of entries in table2 who has table2.id_of_table1 = table1.id
This is my query - it works fine.
$select =array('table1.*', 'COUNT(table2.id) AS `my_count_result`',);
$this->db->select($select);
if($id!=false){ $this->db->where('id',$id); }
$this->db->from('table1 as t1');
$this->db->join('table2 as t2', 't1.id = t2.id_of_table1');
return $this->db->get()->result_array();
Now I have another field which has coma-separated data
table1.next_field = info1, info2, next,...
Now I want to check in the same way like the first query how often for example "info2" is as a part inside the table1.next_field
Is it possible, how?
After all i decide to change my database structure to make the work and handle much easier.

How to use order by query both with current table column and relationship table column in laravel?

i am trying to fetch record with order by query but situation is this that i have to use order by both on current table column and relationship table column in laravel . I tried this
$consignments = Consignment::where('delivery_run_id', $id)->whereIn('status', [
'In Warehouse',
'With On Forwarder',
'In Transit (Warehouse->Delivery)',
'Awaiting Pickup'
])->with(['consignment_run_sheet' => function ($query) {
$query->orderBy('run_sheet_id');
}])->orderBy('delivery_date', 'DESC')->get();
$deliveryRuns = DeliveryRun::all();
How I can achieve it?
it will order just the relation items in this way. solution is use subquery or joins. useing Subquery is like this if assume the modal for consignment_run_sheet relation is ConsignmentRunSheet and the relation is belongsTo:
$consignments = Consignment::where('delivery_run_id', $id)->whereIn('status', [
'In Warehouse',
'With On Forwarder',
'In Transit (Warehouse->Delivery)',
'Awaiting Pickup'
])->with('consignment_run_sheet')
->orderBy(ConsignmentRunSheet::select('delivery_date')
->whereColumn('consignments.id', 'consignment_run_sheet.consignment_id'), 'DESC')
->get()
source:
https://reinink.ca/articles/ordering-database-queries-by-relationship-columns-in-laravel

Query for tables with foreign key in codeigniter

I have 2 tables SjohlLBzads_products & SjohlLBzads_products_meta connected by column (post_id) as foreign key.
How do I create queries on multiple tables ?
Controller function which I have right now only makes query to a single table (SjohlLBzads_products).
I would like to display shipping column in SjohlLBzads_products_meta together with other columns from the current table.
public function index(){
$this->load->library('lib_pagination');
$pg_config['sql'] = "SELECT * from SjohlLBzads_products";
$pg_config['per_page'] = 50;
$data = $this->lib_pagination->create_pagination($pg_config);
$this->load->view("product_listing", $data);
Thanks!
Use a JOIN statement
$pg_config['sql'] = "SELECT * FROM SjohlLBzads_products
JOIN johlLBzads_products_meta
ON johlLBzads_products.post_id = johlLBzads_products_meta.post_id ";

Conditional Select Statement in laravel eloquent

I have a raw query like that
SELECT IF(`user_group` = '1', `total_score`, `score`) FROM `user`
Now how I can convert this query in laravel eloquent ORM
Convert the MYSQL CASE INTO LARAVEL Query
$query = DB::raw("(CASE WHEN user_group='1' THEN 'Admin' WHEN user_group='2' THEN 'User' ELSE 'Superadmin' END) as name");
and simply execute this query in
DB::table('tablename')->select($query)->get();
or
YourModelClass::select($query)->get();
You will get the result.
Applicable if you need to have conditional join and select :
Using mysql's native conditionals can be a good way. You might be in a situation where if a particular condition is truthy in PHP then you need to join that table otherwise do not join.
For example :
If $loggedInUser is admin, then you want to get student attendence otherwise just show marks.
you can have(PS below is a pseudo code just for reference) :
<?php
// Having the column selection only when a particular condition is true
// Else have its value as NULL(You can have NA also)
if($loggedInUser->role == 'admin'){
$attendanceColumnSelect = DB::raw('attendance.total as total_attendance');
}
else{
$attendanceColumnSelect = DB::raw('NULL as total_attendance');
}
// Students query with joins which must be there always
$studentsQuery= Students::select('name', 'class', 'age', $attendanceColumnSelect)
->join('someothertable', 'someothertable.student_id', '=', 'student.id');
// Adding join of attendance only when required for admin role
if($loggedInUser->role == 'admin'){
$studentsQuery->join('attendance', 'attendance.student_id', '=', 'student.id');
}
// Getting final data
$finalResult = $studentsQuery->get();
?>
If you try to do this way :
<?php
$finalResult = DB::select("
SELECT students.name,
students.class,
students.age,
IF('$loggedInUser->role' = 'admin', attendance.total, NULL) as total_attendance
FROM students
INNER JOIN someothertable on someothertable.student_id = student.id
INNER JOIN attendance on attendance.student_id = student.id
");
?>
Then you have to have the attendance join even when you know the condition is false because otherwise it will have 'unknown column attendance.total' error.
From my perspective, if we know we do not want a particular column, I would just not join that table. If you do an EXPLAIN on above raw query, you will find MySQL will need attendance table even when the If condition in select is false.
Please feel free to comment if you find this incorrect or any better suggestions.
DB::table('users')->select('IF(`user_group` = '1', `total_score`, `score`)')->get();
this will work

Resources