I'm querying DB in laravel 4 but can't access the returned value here is the code :
public static function getCityIdByName($cityname){
$cityid = DB::select( DB::raw(" SELECT id FROM cities WHERE match(city_name) against('*" .
$cityname . "*' IN BOOLEAN MODE ) " ));
return $cityid;
}
so the function returns this [{"id":1}] and I need to get value "1", I tried $cityid->id and $cityid['id'] and $cityid[0] but it all returns an error , also it is not a string , when I echo it, it complains that array is not a string Array to string conversion
I solved the problem with this code :
return $cityid[0]->id;
thanks to # Sylwit
Even if it works you can improve it
If you have several results you would take only the first of the array while you would maybe take care of all results.
You can also use ->first() in your query to get only the first object which will avoid you to use the [0].
An interesting link
https://laracasts.com/discuss/channels/eloquent/is-this-match-against-using-relevance-possible
Related
I have in my database a column which store a json and I would like to recover the value of a certain object of my json in order to test it
So my column "JSON" contains that
{
"type":"index",
"data ":{"index":2}
}
And if i receive 2, i need to get this column which contain the index 2 to delete it
I have tried this:
$column = Table::where('JSON["data"]["index"]','=', '2' )
->first();
Table::dropColumn($column);
But it doesn't work, beacause i can't get the index
If you are using latest laravel version then,
$column = Table::where('JSON->data->index','2')->first();
Should work.
You can refer official laravel documentation for json where clause here.
Simply use SQL Like
->where('JSON', 'like', '%"index": "2"%');
Since you gave JSON value as a string, it was unable to get the index value.
Can you please try like below,
$column = Table::whereRaw(JSON["data"]["index"], '=', '2' )
->first();
Table::dropColumn($column);
This question already has answers here:
Select Last Row in the Table
(22 answers)
Closed 4 years ago.
public function addNewPost(Request $request)/****ADD new POST****/
{
$this->validate($request,['post_title'=>'required|min:4|max:100',
'post_description'=>'required|min:20|max:500'
]);
$user_name = Session::get('name');
$post_title = $request->input('post_title');
$post_description = $request->input('post_description');
$addPost = new AddNewPost(['user_name'=> $user_name, 'post_title'=> $post_title, 'post_description'=> $post_description]);
$addPost->save();
$addPost->post_id;
//$addPost = DB::table('userposts')->where(['user_name'=>$user_name ])->orderBy('post_id', 'desc')->get();
print_r($addAdmin->post_id); //This is printing nothing, i.e. blank.
}
post_id column in userposts table is auto incremented. I am trying to get the last post id of the user by user_name. I have seen some tutorials and also checked some questions over internet but unable to do what I am trying to get. Can anybody know how to do it. Thank you.
Try first() instead of get() in a query it might help you
$lastdata = DB::table('userposts')->where(['user_name'=>$user_name ])->orderBy('post_id', 'desc')->first();
print_r($lastdata);
Laravel has the last() method that you can use.
This is from the docs:
last()
The last method returns the last element in the collection that passes a given truth test:
collect([1, 2, 3, 4])->last(function ($value, $key) {
return $value < 3;
});
// returns 2
You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:
collect([1, 2, 3, 4])->last();
//returns 4
Here is the example for getting only the last id:
Model::pluck('id')->last();
DB::table('userposts')->last()->pluck('user_name') Is the fastest way .
Make sure to apply last() first to avoid unnecessary workload
Simple method which will not takes much processing is
DB::getPdo()->lastInsertId();
Hope this helps
You can also try
$addPost = new AddNewPost(['user_name'=> $user_name, 'post_title'=> $post_title, 'post_description'=> $post_description]);
$addPost->save();
$addPost->update();
print_r($addPost->post_id); //It will print id..
P.S second method is kind of redundant
Hope this helps
Please have a closer look at your print statement:
print_r($addAdmin->post_id);
The $addAdmin is not defined within the scope of your function. The best way to get the last row from your database:
DB::table('name_of_table')->last()->pluck('user_name')
Here is the documentation on using DB: https://laravel.com/docs/5.6/database
I have this following Yii 2 query
$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->all();
So imagine this query was an array. Everything found by this query has an "id" attribute.
Since it's sorted by "totals", I essentially want to return the position in the array where I can find this specific id.
Currently, I'm using this code.
foreach ($find as $t) {
$arr[] = $t->id;
if ($t->id == $id) {
break;
}
}
$key = count($arr);
return $key;
However, this code is vany wayow on a 100k+ result query.
Is there anyway to speed this up?
You could get the result as an array (instead of object) as
$find = People::find()->where(['c_id' => $c_id])
->orderBy('totals DESC, id DESC')
->asArray()
->all();
then you could find your value using array_search()
$my_index = array_search($id,$find);
but for 100k+ you should find using a direct select in db...instead tha looping on php or load all in php and scan with array_search()
To get array from query in YII, you can use queryAll();
$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->queryAll();
OR, another way to convert the object into an array is:
$find = json_decode(json_encode($find), true); // to convert all data into array.
And once you get results in array, you can implement the actual code for your requirement as given below.
You can use array_search() function to get index of your value.
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
The array_search() function search an array for a value and returns the key.
Maybe I didn't understand you correctly but I assume that you are trying to detect the index or key for your desired id inside an array returned from an SQL query that is sorted by some other column like total.
So let us fetch records from the database with your query with a little change asArray() like this
$find = People::find()
->where(['c_id' => $c_id])
->orderBy('totals DESC, id DESC')
->asArray()
->all();
in the result, let us assume the People table returns you an array with the following dataset ordered by columns total and id DESC.
[
0 => [
'id' => 2 ,
'c_id'=>2,
'name' => 'John' ,
'age'=>18,
'totals'=>100,
],
1=>[
'id'=>1,
'c_id'=>55,
'name'=>'Bob',
'age'=>20,
'totals'=>80,
],
2=>[
'id'=>3,
'c_id'=>85,
'name'=>'Peter',
'age'=>15,
'totals'=>75,
]
];
Now if you look into \yii\helpers\ArrayHelper you will find ArrayHelper::getColumn().
Let us use this on the array we received from the query, I assume that you are searching $id inside the column id so we will first filter out the id column like below.
$idsArray = ArrayHelper::getColumn($find, 'id');
this will give us the ids in the following sequence which is in the same order as the initial result set.
[2,1,3]
then lets use the built-in php function array_search()
$key=array_search($yourId,$idsArray);
Hope this is what you are looking for.
Now I admit I am slightly new to laravel still, but to me this just does not make sense. The model that goes along with this table contains only 2 functions, both containing a relationship statement.
I am using Laravel4, mysql, php 5.5
Any ideas are welcome :D
The database record-definitions are for both DATETIME, allow null and no default value (changed that after the screenshots)
the $challenge variable is part of the data I pass on to the view like so:
$challenges = Auth::user()->challenges;
$data['challenges'] = $challenges;
return View::make("challenges/topic", $data);
and in the view I use
#foreach($challenges as $challenge)
read the challenge values (I am aware I cant echo like that without php tags or {{ }}, just easier to explain)
echo gettype($challenge->deadline) // results in string
echo gettype($challenge->created_at) // results in object
Depends on how you access it, if you do:
Route::any('test', ['as' => 'test', function()
{
$a = Article::first();
var_dump( gettype($a->created_at) );
$a = DB::table('articles')->first();
var_dump( gettype($a->created_at) );
}]);
You will get:
string 'object' (length=6) /// This is Eloquent
string 'string' (length=6) /// This is the QueryBuilder directly accessing your table
I am trying to extract ONLY the PlanDetails where PlanDetail.company_id = Company.id AND PlanDetail.id' => $id.. ( you can see the conditions in my controller below)..
Controller:
function pd_list_by_company($id = null) {
$this->recursive = 2; // I am going to use containable to trim this.
return $this->PlanDetail->find('all',
array('conditions' =>
array('AND' =>
array('PlanDetail.company_id' => 'Company.id',
array('PlanDetail.id' => $id)))));
}
Test View:
$planDetailsByCompany = $this->requestAction('/planDetails/pd_list_by_company');
debug($planDetailsByCompany );
Output result of my debug??
Array()
If I remove the conditions and just have the find all, I get all PlanDetails as expected, so I know the data is being passed.. SQL debug dump even shows the query:
WHERE ((`PlanDetail`.`company_id` = 'Company.id') AND (`PlanDetail`.`id` IS NULL))
And yes, I did notice the $id is NULL, and I know the value needs to be there.. So maybe my question is why is the $id value not being passed to the controller even though I can see the PlanDetail.id value on a find('all') w/ out the conditions??
Thanks for any tips.
Since $id seems to be null, I would assume that you call the function without the parameter. And you don't get an error message, because as far as PHP is concerned the parameter is optional. In this case it's clearly required, so you should make it a required parameter in your function declaration:
function pd_list_by_company($id) {
Also you could simplify the return statement, you do not need the AND:
return $this->PlanDetail->find('all',
array('conditions' =>
array('PlanDetail.company_id' => 'Company.id','PlanDetail.id' => $id)
)
);
To answer the question why is the $id not being passed is because you're not passing it
To pass say $id of 2 you need to do the following in your requestAction
$this->requestAction('/planDetails/pd_list_by_company/2');
Seems to me that your code should just be
return $this->PlanDetail->find('array('PlanDetail.id' => $id));
Assuming you have the $this->PlanDetail->recursive flag set to > 0, your Model should already know about and return the associated data for any 'Company' table.....
I'm used to an old (1.3) version of CakePHP but the find() function is pretty basic and is designed to only return one row.
and yes, you definitely need to call the function with the id appended to the url, eg.
$planDetailsByCompany = $this->requestAction('/planDetails/pd_list_by_company/999');