Get current time in select in laravel - laravel

$product = Product::select('id', 'name', 'status',DB::raw('date(\'d-m-y\') as dateCurrent' ))
->whereDate('status', 3)
->get()
->toArray();
Result dateCurrent null :
Array
(
[0] => Array
(
[id] => 4
[name] => 'Iphone'
[dateCurrent] => null
)
[1] => Array
(
[id] => 5
[name] => 'samsung'
[dateCurrent] => null
)
)
I want to get current time right at select. Is there any way to get it? Thanks

date('d-m-y')
looks like php built function
if u want to db time
u can use NOW() function
and if u use db time
$product = Product::select('id', 'name', 'status', DB::raw('NOW() AS dateCurrent'))
->whereDate('status', 3)
->get()
->toArray();
but u want php server time
$product = Product::select(
'id', 'name',
'status', DB::raw(sprintf('%s AS dateCurrent', date('d-m-y'))))
->whereDate('status', 3)
->get()
->toArray();
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_now

Related

I need To All Data In $qryy It Return Only Last Record

How I Return all data of $qryy it's return me only last record. How I need return all off data.
public function get_subcategory(){
$qry = $this->db->get("shopping_category");
foreach($qry->result() as $row){
$this->db->where("c_id",$row->id);
$qryy = $this->db->get("shopping_subcategory");
}
return $qryy;
}
You can try this
public function get_subcategory() {
$result = [];
$qry = $this->db->get("shopping_category");
foreach ($qry->result() as $row) {
$this->db->where("c_id", $row->id);
$qryy = $this->db->get("shopping_subcategory");
$result[] = $qryy;
}
return $result;
}
The reason you get the last record is, every time you loop data through foreach it keeps replacing $qryy = $this->db->get("shopping_subcategory");
to fix this you can simply change $qryy into an array $qryy[] like this.
To improve your query. you can simply try
$qryy = [];
$this->db->select("shopping_subcategory.*");
$this->db->from("shopping_category");
$this->db->join('shopping_subcategory', 'shopping_category.id = shopping_subcategory.c_id');
$sql= $this->db->get();
$qryy = $sql->result_array();
$data['category'] = $qryy;
$this->load->view('view_name', $data);
In view
$category will show your data
I think it solve your problem. would you mind if you give it a try?
since you want from table shopping_category is only id i try to fetch it so it's not a heavy duty on your server.
$result = [];
$qry = $this->db->select("id")->get('shopping_category');
foreach ($qry->result() as $row) {
$this->db->where("c_id", $row->id);
$qryy = $this->db->get("shopping_subcategory")->result();
$result[] = $qryy;
}
return $result;
Hope that helps :)
you should use another approach to resolve your problem: use joins to query the database only once:
$this->db->join("shopping_subcategory t2","t2.c_id=t1.id");
$qry = $this->db->get("shopping_category t1");
return $qry->result();
if you output above with print_r($qry->result()), you get similar to below:
Array
(
[0] => stdClass Object
(
[ID] => 1
[company_ID] => 1
[name] => aaa
)
[1] => stdClass Object
(
[ID] => 2
[company_ID] => 1
[name] => bbb
)
[2] => stdClass Object
(
[ID] => 4
[company_ID] => 2
[name] => ccc
)
)
to resolve your approach: you need to make $qryy an array, to store each subquery data, right now you are overwriting the variable $qryy with each loop and therefore only get the last result:
$qry = $this->db->get("shopping_category");
$qryy=array();
foreach($qry->result() as $i=>$row){
$this->db->where("c_id",$row->id);
$qryy[$i] = $this->db->get("shopping_subcategory")->result();
}
return $qryy;
if you output above with print_r($qryy), you get similar to below:
Array
(
[0] => Array
(
[0] => stdClass Object
(
[ID] => 1
[company_ID] => 1
[name] => aaa
)
[1] => stdClass Object
(
[ID] => 2
[company_ID] => 1
[name] => bbb
)
)
[1] => Array
(
[0] => stdClass Object
(
[ID] => 4
[company_ID] => 2
[name] => ccc
)
)
)
therefore, depending which approach you use, you'll need to take care of your data output differently.
helpful info on joins here

In eloquent fetching data in fieldname=>fieldvalue keys

In laravel 5.8 making request
$searchResultsArray = SearchResult
::getBySourceId($next_sourceId['source_id'])
->select( 'field', 'value' )
->get()
->toArray();
I got resulting rows like :
$searchResultsArray::Array
(
[0] => Array
(
[field] => Id
[value] => 302530
)
[1] => Array
(
[field] => Domain
[value] => site.com
)
If there is a way to get
array of fieldname=>fieldvalue keys, like
Id => 302530
Domain=> site.com
without additive foreach block in my code?
If yes how?
Yes there is. Eloquent always returns collections. You could modify the collection first with mapWithKeys() (https://laravel.com/docs/5.8/collections#method-mapwithkeys) and then convert it to an array.
Try something like this:
$searchResultsArray = SearchResult
::getBySourceId($next_sourceId['source_id'])
->select( 'field', 'value' )
->get()
->mapWithKeys(function ($item) {
return [$item['field'] => $item['value']];
})
->all();

Laravel insert or update multiple rows

Im new in laravel, and im trying to update my navigation tree.
So i want to update my whole tree in one query without foreach.
array(
array('id'=>1, 'name'=>'some navigation point', 'parent'='0'),
array('id'=>2, 'name'=>'some navigation point', 'parent'='1'),
array('id'=>3, 'name'=>'some navigation point', 'parent'='1')
);
I just want to ask - is there posibility in laravel to insert(if new in array) or update my current rows in database?
I want to update all, because i have fields _lft, _right, parent_id in my tree and im using some dragable js plugin to set my navigation structure - and now i want to save it.
I tried to use
Navigation::updateOrCreate(array(array('id' => '3'), array('id'=>'4')), array(array('name' => 'test11'), array('name' => 'test22')));
But it works just for single row, not multiple like i tried to do.
Maybe there is another way to do it?
It's now available in Laravel >= 8.x
The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is an array of columns that should be updated if a matching record already exists in the database:
Flight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);
I wonder why this kind of feature is not yet available in Laravel core (till today). Check out this gist The result of the query string would look like this: here
I am putting the code here just in case the link breaks in the future, I am not the author:
/**
* Mass (bulk) insert or update on duplicate for Laravel 4/5
*
* insertOrUpdate([
* ['id'=>1,'value'=>10],
* ['id'=>2,'value'=>60]
* ]);
*
*
* #param array $rows
*/
function insertOrUpdate(array $rows){
$table = \DB::getTablePrefix().with(new self)->getTable();
$first = reset($rows);
$columns = implode( ',',
array_map( function( $value ) { return "$value"; } , array_keys($first) )
);
$values = implode( ',', array_map( function( $row ) {
return '('.implode( ',',
array_map( function( $value ) { return '"'.str_replace('"', '""', $value).'"'; } , $row )
).')';
} , $rows )
);
$updates = implode( ',',
array_map( function( $value ) { return "$value = VALUES($value)"; } , array_keys($first) )
);
$sql = "INSERT INTO {$table}({$columns}) VALUES {$values} ON DUPLICATE KEY UPDATE {$updates}";
return \DB::statement( $sql );
}
So you can safely have your arrays inserted or updated as:
insertOrUpdate(
array(
array('id'=>1, 'name'=>'some navigation point', 'parent'='0'),
array('id'=>2, 'name'=>'some navigation point', 'parent'='1'),
array('id'=>3, 'name'=>'some navigation point', 'parent'='1')
)
);
Just in case any trouble with the first line in the function you can simply add a table name as a second argument, then comment out the line i.e:
function insertOrUpdate(array $rows, $table){
.....
}
insertOrUpdate(myarrays,'MyTableName');
NB: Be careful though to sanitise your input! and remember the timestamp fields are not touched. you can do that by adding manually to each arrays in the main array.
I've created an UPSERT package for all databases: https://github.com/staudenmeir/laravel-upsert
DB::table('navigation')->upsert(
[
['id' => 1, 'name' => 'some navigation point', 'parent' => '0'],
['id' => 2, 'name' => 'some navigation point', 'parent' => '1'],
['id' => 3, 'name' => 'some navigation point', 'parent' => '1'],
],
'id'
);
Eloquent Style
public function meta(){ // in parent models.
return $this->hasMany('App\Models\DB_CHILD', 'fk_id','local_fk_id');
}
.
.
.
$parent= PARENT_DB::findOrFail($id);
$metaData= [];
foreach ($meta['meta'] as $metaKey => $metaValue) {
if ($parent->meta()->where([['meta_key', '=',$metaKey]] )->exists()) {
$parent->meta()->where([['meta_key', '=',$metaKey]])->update(['meta_value' => $metaValue]);
}else{
$metaData[] = [
'FK_ID'=>$fkId,
'meta_key'=>$metaKey,
'meta_value'=> $metaValue
];
}
}
$Member->meta()->insert($metaData);
No, you can't do this. You can insert() multiple rows at once and you can update() multiple rows using same where() condition, but if you want to use updateOrCreate(), you'll need to use foreach() loop.
I didn't find a way to bulk insert or update in one query. But I have managed with only 3 queries. I have one table name shipping_costs. Here I want to update the shipping cost against the shipping area. I have only 5 columns in this table id, area_id, cost, created_at, updated_at.
// first get ids from table
$exist_ids = DB::table('shipping_costs')->pluck('area_id')->toArray();
// get requested ids
$requested_ids = $request->get('area_ids');
// get updatable ids
$updatable_ids = array_values(array_intersect($exist_ids, $requested_ids));
// get insertable ids
$insertable_ids = array_values(array_diff($requested_ids, $exist_ids));
// prepare data for insert
$data = collect();
foreach ($insertable_ids as $id) {
$data->push([
'area_id' => $id,
'cost' => $request->get('cost'),
'created_at' => now(),
'updated_at' => now()
]);
}
DB::table('shipping_costs')->insert($data->toArray());
// prepare for update
DB::table('shipping_costs')
->whereIn('area_id', $updatable_ids)
->update([
'cost' => $request->get('cost'),
'updated_at' => now()
]);
in your controller
use DB;
public function arrDta(){
$up_or_create_data=array(
array('id'=>2, 'name'=>'test11'),
array('id'=>4, 'name'=>'test22')
);
var_dump($up_or_create_data);
echo "fjsdhg";
foreach ($up_or_create_data as $key => $value) {
echo "key ".$key;
echo "<br>";
echo " id: ".$up_or_create_data[$key]["id"];
echo "<br>";
echo " Name: ".$up_or_create_data[$key]["name"];
if (Navigation::where('id', '=',$up_or_create_data[$key]["id"])->exists()) {
DB::table('your_table_ name')->where('id',$up_or_create_data[$key]["id"])->update(['name' => $up_or_create_data[$key]["name"]]);
}else{
DB::insert('insert into your_table_name (id, name) values (?, ?)', [$up_or_create_data[$key]["id"], $up_or_create_data[$key]["name"]]);
}
}

codeignite trying to get property of non-object not resolved

I am attempting to access the result set from a model query in the view. I have the following:
Controller:
$courseId = $this->session->userdata('courseId');
//echo "Course: ".$courseId;
if(isset($courseId) && $courseId != '')
{
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
}
Model:
function loadBasicDetailsEdit($courseId)
{
$this->db->select('*');
$this->db->where('course_id', $courseId);
$this->db->from('course');
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
return $query->result();
} else {
return FALSE;
}
}
and in the view I tried to print_r() and got this:
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
I tried to access this using $basicCourseDetails->title or $basicCourseDetails['title']
but neither are working. Any hint as to why this is happening?
Regards,
try this:
foreach($basicCourseDetails as $basic){
echo($basic->title);
}
or something like this:
echo($basicCourseDetails[0]->title);
This is an array of objects
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
Contains one stdObject in the array, so, first objects is 0, if there were more, then second item could have index 1 and so on. To retrieve data from the first (here is only one) stdobject you may use
echo $basicCourseDetails[0]->title; // title will be printed
You can send data to the view page by this line of code which is mentioned in above question.
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
But when you will access these data in view then you need to access all data one by one by using foreachloop in the view page.
For example if you have a view page like basic_details.php inside course folder then you need to write code like this to access these data.
foreach ($basicCourseDetails as $key => $value) {
$name = $value->name;
}
The above foreachloop can be written in view page where you want to access data.

Use Array Data in CodeIgniter Model as SQL?

In my controller, I am passing data to the model using the following code:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
var_dump($data);
$this->Login_model->insert_entry($data);
In my model, what I want to do is use the gid value as part of an SQL statement, like so:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = $gid');
Obviously this doesn't work, so I'm just wondering how I get the gid from $data and use it in my SQL statement?
Tested using
$get_gid = $this->db->where('gid', $data['gid'])->get('users');
print_r($get_gid);
However output is:
CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id]
=> Resource id #33 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0
[num_rows] => 0 [row_data] => )
Did you try gid = $data['gid']
I assume that yours model method looks like this:
insert_entry($data)
{
here active record or query...
}
If yes try to display query to see if $data['gid'] is visible there
You can try it by
$this->db->get_compiled_select();
Or after query runs
$this->db->last_query();
Try this way:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
$gid = $data['gid'];
$this->db->where('gid',$gid);
$this->db->from('users');
$query = $this->db->get();
if($query)
{
//you can return query or you can do other operations here like insert the array data
//$this->db->insert('yourtable',$data);
return $query;
}
else
{
return FALSE;
}
You can try:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = '.$data['gid'].');
You just Forget after query $query->result().

Resources