CONCAT_WS not working on select statement - activerecord

Im trying to concatenate "firstname" and "lastname" like this "firstname lastname"
while doing a search query.
here's my code:
$query = Contact::find()
->select([
"CONCAT_WS(' ', firstname, lastname) AS name"
])
->where('(firstname like :fname) OR (lastname like :lname) OR (email = :email)', [
':fname' => $searchkey,
':lname' => $searchkey,
':email' => $searchkey,
])->all();
but the result is empty like this:
Array
(
[0] => common\models\contact\Contact Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
)
[_oldAttributes:yii\db\BaseActiveRecord:private] => Array
(
)
[_related:yii\db\BaseActiveRecord:private] => Array
(
)
[_errors:yii\base\Model:private] =>
[_validators:yii\base\Model:private] =>
[_scenario:yii\base\Model:private] => default
[_events:yii\base\Component:private] => Array
(
)
[_behaviors:yii\base\Component:private] => Array
(
)
)
)
I'm expecting that i'll have something like this
[name] => "firstname lastname"
output but no luck. need help thanks.

You should add a public var $name in your Contcat model and add attribute as safe in rules for recive the calculated value with alias name
class Contact extends \yii\db\ActiveRecord
{
public $name;
....
}

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

Axios Delete not working

In my CRUD webapp based on Laravel 5.6 and Vue.js 2 Add, Edit and Show are working fine. But Delete is not working because axios.delete is not sending id to controller. Console.log in Home.vue is showing correct id and key values. Following is the code and result what I am getting in controller. Please tell my mistake. Also do I really need a Route for delete in web.php?
Controller
public function destroy(Sms $sms)
{
$myfile = fopen("newfile.txt", "w", true) or die("Unable to open file!");
$txt = "Print_r: ". print_r($sms) ."\r\nID: ". $sms->id;
//fwrite($myfile, $txt);
fwrite($myfile, print_r($sms, TRUE));
//die();
Sms::where('id',$sms->id)->delete();
}
Home.vue
del(key,id){
if(confirm("Are you sure?")){
this.loading = !this.loading
/*axios.delete(`/sms/${id}`)*/
axios.delete(`sms/${id}`, {params: {id: `${id}`}})
.then((response)=> {this.lists.splice(key,1);this.loading = !this.loading})
.catch((error)=> this.errors = error.response.data.errors)
console.log(`KEY:${key} ID:${id}`);
}
}
web.php
Route::delete('sms/{id}', 'smsController#destroy');
newfile.txt
App\Sms Object
(
[hidden:protected] => Array
(
[0] => created_at
[1] => updated_at
)
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] =>
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
)
[original:protected] => Array
(
)
[changes:protected] => Array
(
)
[casts:protected] => Array
(
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[appends:protected] => Array
(
)
[dispatchesEvents:protected] => Array
(
)
[observables:protected] => Array
(
)
[relations:protected] => Array
(
)
[touches:protected] => Array
(
)
[timestamps] => 1
[visible:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
)
try to change axios.delete to axios.post, and add a _method field with the value delete in the data to be sent. like so
axios.post(`sms/${id}`, {params: {id: `${id}`}, _method: 'delete'})

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().

Best way to make selects in laravel?

In order to use the Form::select, you need to add a name and two arrays.
In a normal case, we have one with the id and another one with the name. Both needs to be loaded from a query.
So in the model I have something like this:
public static function get_ids()
{
//return DB::query('select id FROM __roles');
return DB::table('roles')->get(array('id'));
}
//Returns an array with all the names
public static function get_names()
{
//return DB::query('select name FROM __roles');
return DB::table('roles')->get(array('name'));
}
However, this gives me this:
Array ( [0] => stdClass Object ( [id] => 1 ) [1] => stdClass Object ( [id] => 2 ) [2] => stdClass Object ( [id] => 3 ) )
I would like to get something like this:
Array ( [0] => '1' [id] => '2' [id] => '3' )
For the form
Form::select('role', array(Role::get_ids(), Role::get_names()));
Does this work?
public static function get_ids()
{
//return DB::query('select id FROM __roles');
return DB::table('roles')->get(array('id'))->to_array();
}
//Returns an array with all the names
public static function get_names()
{
//return DB::query('select name FROM __roles');
return DB::table('roles')->get(array('name'))->to_array();
}
I tried this option:
$projects = Project::where('user_id', Auth::user()->id)->lists('name', 'id');
In template:
{{ Form::select('project', $projects) }}

Multi-dimensional array parsed from .csv ->commas causing mysql database insert issues

I am using Codeigniter to parse an uploaded csv file (which is a multi-dimensional array) into a database. I have tried everything to parse the comma values correctly, but the "id" column in mysql comes up short, as it reads "text", and not "text,text,text". Help!?
*For reference:*
print_r($data['csvData']);
Array ( [0] => Array ( [category,id] => text1,"text,text,text" )
[1] => Array ( [category,id] => text2,"text,text,text" )
)
foreach($data['csvData'] as $row) {
foreach ($row as $item) {
$item=explode(",", $item);
$results_array = array(
'category' => $item[0],
'id' => $item[1]
);
$this->db->set($results_array);
$this->db->insert('table', $results_array);
}
}
My uneducated guess:
$item=explode(",", $item); is exploding $item which is text1,"text,text,text", right? So it sees 4 commas, and explodes them. Therefore $item[0] will be "text1, $item[1] will be "text" $item[2] will be "text" and $item[3] will be "text".
You can try to set your delimiter in the csv as something other than a comma, and explode that.
Or you can concatenate the other items before inserting them into the db:
$item = explode(",", $item);
$id_insert = $item[1].$item[2].$item[3];
//if you need to retain the commas in the id:
//$id_insert = $item[1].','.$item[2].','.$item[3];
$results_array = array(
'category' => $item[0],
'id' => $id_insert,
);
$this->db->set($results_array);
$this->db->insert('table', $results_array);

Resources