I have tried to get all column names from a table Teller
Function:
public function getTableColumns($tables)
{
return DB::select(DB::raw('SELECT
COLUMN_NAME,
DATA_TYPE,
COLUMN_DEFAULT
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
table_name = `Teller`'));
}
You can get all columns name by simply doing that...
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
public function getTableColumns($table)
{
return DB::getSchemaBuilder()->getColumnListing($table);
// OR
return Schema::getColumnListing($table);
}
Get Table Name From Model
$product = new Product;
$table = $product->getTable();
print_r($table);
Get Table Column Name From Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function getTableColumns() {
return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
}
}
Now you will get all columns of "products" table and if you need it in controller then you can get it by following way :
$product = new Product;
$columns = $product->getTableColumns();
print_r($columns);
Just in-case if you have multiple databases connections, try following:
Add in the top of your php script
use Illuminate\Support\Facades\Schema;
Retrieve anywhere in your code
With Database Connection
$columns = Schema::Connection('business')->getColumnListing('users'); // 'business' is your database connection
echo "<pre>";
print_r($columns);
exit();
Without Database Connection
$columns = Schema::getColumnListing('users');
echo "<pre>";
print_r($columns);
exit();
You only need extract the keys from the query response
array_keys(json_decode(json_encode($table[0]), true))
As of Laravel 6.x this works:
$db = DB::connection()->getPdo();
$rs = $db->query('SELECT * FROM Teller LIMIT 0');
for ($i = 0; $i < $rs->columnCount(); $i++) {
$col = $rs->getColumnMeta($i);
$columns[] = $col['name'];
}
print_r($columns);
The hint here is just to go around eloquent (which should just provide a simple way to do this, but clearly does not) and grab the PDO object and then use the answer from the same question for straight PDO access
This will also work when there is no database selected by replacing 'Teller' with databasename.Teller
HTH,
-ft
Another way from a model using collections.
collect(User::first())->keys();
#Eduardo Wallace method has it simplest; just return the first value from the table, strip off the values leaving the keys
$T1 = table_name::first();
$table_columns = array_keys(json_decode($T1, true));
If you don't need all the columns, strip away unneeded columns, leaving only the ones needed:
$needed_columns = array_diff($table_columns, ['unneeded_1', 'unneeded_2']);
You can argue the method used, simplest to me anyways!
$db = [];
$tables = DB::select('SHOW TABLES');
foreach ($tables as $key => $table) {
$name = $table->Tables_in_app;
$app[$name] = DB::getSchemaBuilder()->getColumnListing($name);
}
return $db;
You can get an idea with this script
$columns = array();
foreach(\DB::select("SHOW COLUMNS FROM $table") as $column)
{
//print_r($column);
$columns[$column->Field] = '';
}
return $columns;
in 12.17.22 it's
extremely simple
$columns=Schema::getColumnListing('my_table_name');
//e.g. your table's name is 'my_table_name' or 'Teller' or 'posts'
// and then
$fetchedSet= Post::select($columns)->where('sender_id','>',100)->get();
And you are done
You could simply write:
public function getTableColumns($tables)
{
return DB::select(
DB::raw('SELECT * FROM `Teller`')
);
}
If you have a Teller model you can also use Teller::all();
Update
To get all column name you can run SHOW FIELDS Teller
You can use this
DB::table('table_name')->get();
Related
I want to get the data form database table and create a new row in another table.
Which 1 PO have many PoProducts.
$_getPO = Order::find($id);
$_getPOProducts= OrderProducts::where('order_id', $id)->get();
$order_no = $_getPO->order_no;
$eta = $_getPO->eta;
$_Order = new DeliveryOrders();
$_Order->order_no = $order_no;
$_Order->eta = $eta;
$_Order->save();
$POProduct = array();
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[] = new DeliveryOrderProducts();
$POProduct[] = $_getPOProduct->order_id;
$POProduct[] = $_getPOProduct->item_id;
$POProduct[] = $_getPOProduct->qty;
$POProduct->save();
}
But, this output an error.
Call to a member function save() on array
Please help me. Thanks.
If you wish to copy records from one table to another or just duplicate a record in the same table you could simply use the repliacate() method.
$user = User::findOrFail($id);
// replicate (duplicate) the data
$staff = $user->replicate();
// make into array for mass assign.
//make sure you activate $guarded in your Staff model
$staff = $staff->toArray();
Staff::firstOrCreate($staff);
Note: in case you're only duplicating on the same table replace Staff with User on this example.
You are trying to run the save method on the array but what you want is to use it on the array index instead.
Change your foreach to this and it should work (assuming columns are the same).
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[$i] = new DeliveryOrderProducts();
$POProduct[$i]->order_id = $_getPOProduct->order_id;
$POProduct[$i]->item_id = $_getPOProduct->item_id;
$POProduct[$i]->qty = $_getPOProduct->qty;
$POProduct[$i]->save();
}
You can shorten this by using forceCreate.
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[$i] = (new DeliveryOrderProducts())->forceCreate($_getPOProduct->only(['order_id', 'item_id', 'qty']));
}
I want to delete all comments from comments table.I did that by doing this but this is not the laravel way. Anyone answer the correct steps please .
$comments = Comment::where('post_id',$id)->get();
if(count($comments)>1)
{
$comment_id= [];
foreach ($comments as $i)
{
$comment_id[] = $i->id;
}
for($i=0;$i<count($comments);$i++)
{
Comment::find($comment_id[$i])->delete();
}
}
elseif (count($comments)==1)
{
$comments->delete();
}
Since each Eloquent model serves as a query builder, try this, all in one line:
Comment::where('post_id',$id)->delete();
Tested in tinker, works as expected, returns count of deleted rows.
Documentation: https://laravel.com/docs/5.3/queries#deletes
You can try the following approach:
public function deleteAll(Request $request)
{
$ids = $request->ids;
Comment::whereIn('id',explode(",",$ids))->delete();
}
DB::table('users')->whereIn('id', $ids_to_delete)->delete();
or
$org-products()->whereIn('id', $ids)->delete();
Collect only ids from your command like below and destroy by model.
$yourRaws = YourModel::where('name', 'Enver')->get();
...
YourModel::destroy($yourRaws->pluck('id')->toArray());
Enjoy Your Coding !
i have a select field named categories[] with multiple select and i written one on change function so on change fuction it will go the controller as an array of id's now what i want is i want to select foods from mysql table with these categories
<select name="categories[]">
<?php
foreach ($category as $c) {
?>
<option value="<?php echo $c->category_id; ?>"><?php echo $c->category_name;?></option>
<?php
}
?>
</select>
controller
public function get_foods(){
$categories = $this->input->post(NULL,true);
$sql = $this->subscription->get_foods($categories);
$result = array(
'result' => $sql
);
echo json_encode($result);
}
and model
public function get_foods($id){
$sql = "SELECT * FROM food_category fc
LEFT JOIN food f ON fc.food_id=f.food_id
WHERE f.food_status = 1 AND
fc.category_id = $id
ORDER BY f.food_id DESC";
$query = $this->db->query($sql);
return $query->result_array();
}
i want to fetch all the foods in these categories, so i think i should have to use some multiple where condition ?
You just need to store category with each food and when you get the foods you can use a where condition :
$this->db->where('category',$category);
use the where columns in () sql function for this.
for detail description on it. find here
http://www.w3schools.com/sql/sql_in.asp
If this can help, I think you need to post the categories one by one, then get it and put it in one array. Here is a code that may help
public function get_foods()
{
$result = array();
foreach($this->input->post('categories') as $c)
{
$result[] = $this->subscription->get_foods($c);
}
echo json_encode($result);
}
and for the model I suggest making use of AR of CI
public function get_foods($category)
{
$this->db->select('*');
$this->db->from('food_category as fc');
$this->db->join('food as f','fc.food_id = f.food_id','left');
$this->db->where('f.food_status', '1');
$this->db->where('fc.category_id',$category);
$query = $this->db->get();
return $query->result_array();
}
First we make an empty array, then using the foreach in post we get all the foods per category then return them inside the result array.
Hope this helps and if there's any error in the sql since I may have forgotten some of the join, I'd be willing to help again.
How do i use the following insert into query in laravel 5?
INSERT INTO connection2.table (SELECT * from connection1.table);
I am looking for two different connections, Connection1.table record should goes to Connection2.table.
try
$c1 = DB("Connection1")->select("SELECT * from table")
foreach($c1 as $record){
DB("Connection2")->table("table")->insert(get_object_vars($record))
}
Since laravel 5.7+ insertUsing(array $columns, Closure|Builder|string $query) is available,
DOCS: https://laravel.com/api/5.8/Illuminate/Database/Query/Builder.html#method_insertUsing
therefore you can now make this whole query in Laravel chaining style like
DB::table('newTable')->insertUsing(
['column1', 'column2', 'column3',], // ..., columnN
function ($query) {
$query
->select(['column1', 'column2', 'column3',]) // ..., columnN
->from('oldTable');
// optional: you could even add some conditions:
// ->where('some_column', '=', 'somevalue')
// ->whereNotNull('someColumn')
}
);
DB here is set-up in app.php 'aliases' as
'DB' => Illuminate\Support\Facades\DB::class,
#Wistar, Thanks for reply, with your code $record comes with an object class which is not accepted by insert,
it required the array type.
I have used it as follows:
DB::setFetchMode(PDO::FETCH_ASSOC);
$table_records = DB::connection('Connection1')->select("SELECT * from table");
DB::setFetchMode(PDO::FETCH_CLASS);
DB::connection('Connection2')->table("table")->insert($table_records);
Elaborating on how to chunk results in case of large tables. You can of course chunk as you see fit, 5000 is just an example.
$chunk1 = DB("Connection1")->table("table")->orderBy("id")->chunk(5000, function($c1) {
foreach($c1 as $record) {
DB("Connection2")->table("table")->insert(get_object_vars($record))
}
});
$basket_data = DB::table('baskets')->get();
foreach($basket_data as $records)
{
DB::table('basket_after_payments')->insert(get_object_vars($records));
}
I just want to ask if you can select a certain table in the database? There is this code in my
model:
public function select_tables(){
$tables = $this->db->list_tables();
return $tables;
}
and in my controller:
public function maintenance(){
$this->data['title'] = "Inventory Maintenance";
$this->load->vars($this->data);
$this->load->view('homeview');
$selecttable['tablename'] = $this->inventory_model->select_tables();
$this->load->view('maintenance_view', $selecttable);
$this->load->view('footer_view');
}
Here is the printscreen in my view:
There is the list of my tables in the database, what I want is I can only show limited tables, for example I just want to show "tbladditional, tblemployees, tblinventorytype". Is there a syntax where I can select a certain table? An equivalent to this syntax
"Select * from 'tablename' where 'tablename' = 'something'"
It's so confusing so please I really need your help. Thank you so much!!
public function select_tables(){
$tables = $this->db->list_tables();
$req_tables = array("tble1", "table2"); //pass your table names as Array
$tables = array_intersect($tables, $req_tables);
return $tables;
}
This is the programmatic way I can come with. As CI doesn't have any method to retrieve specific table names.
you can put a mixture of Codeigniter and the query result
For example:
$table_list = $this->db->list_tables();
foreach($table_list as $tl)
{
if(strpos(strtolower($tl),'tbladditional')==true ||
strpos(strtolower($tl),'tblemployees')==true ||
strpos(strtolower($tl),'tblinventorytype')==true)
{
$query = "Select * from $tl";
}
}