I am new to laravel. I have an array. It looks like this.
$state=[
1 => "Utah"
2 => "California"
3 => "Nevada"
6 => "Arizona"
]
I am trying to query the table in a database called a county. I want to display all the county that falls in those states which are in the array.
I write a code like this
foreach($state as $st) {
$data= DB::table('state')->Select(County)->where('name','=', $st)->get();
dd($data);
}
This is the code that I wrote. It does only return for the first state then after that, it gets stopped can someone help me. Any kind of help is appreciated.
It stops because dd() is dump and DIE. So it is like you would call:
dump($data);
die();
Try something like:
$query= DB::table('state');
foreach($state as $st) {
$query->orWhere('name','=', $st);
}
$data = $query->get();
It will make one DB call instead of X calls and returns a collection of records with which you can work.
You can try:
DB::table('country')->whereIn('name', array_values($state))->get();
You have to give categories to filter and next join eachother
App\YourModel::select('what you want')->join('category','your_models.id','=','category.your_model_id')->get();
Related
I'm working on a simple search project where I'm returning the results. The search function appears to work however, the total and page return the wrong values. The total field returns the total number of rows inside the data, not the total number of results from the search and the page is always {}.
Here's the model->function I've created:
public function search($string)
{
$results = $this->select('*')->orLike('title', $string)->orLike('excerpt', $string);
if ( empty( $results ) )
{
return [];
} else
{
$data = [
'results' => $results->paginate(2),
'total' => $results->countAllResults(),
'page' => $this->pager,
];
return $data;
}
}
What's puzzling is if I place the total field above the results value the count works, but then the result fields returns everything in the database at paginate(2).
Ok, I managed to solve this query by adding two separate queries to the database. The processing cost appears to be minimal and it should be alright when caching the responses. As it turns out you can chain queries but only in a particular order and if you use grouping (see ->groupStart() )
$results = $this->select('title, image, categories, id, excerpt')->groupStart()->like('title', $search)->orLike('excerpt', $search)->groupEnd()->where('status','live')->paginate(2);
$total = $this->select('title, image, categories, id, excerpt')->groupStart()->like('title', $search)->orLike('excerpt', $search)->groupEnd()->where('status','live')->countAllResults();
Some may argue the inefficiency of the two queries, but this works for my use case :) Hope this helps anyone else stuck on a similar problem.
I've made an API with the Yii2 framework.
But I don't know how to use the OR condition in my statement.
For example:
I want to get all cars with brand BMW or DODGE.
I've tried the following:
$query = Car::getCar($lang)
->where(['or', ['m.brand' => 'BMW'], ['m.brand' => 'DODGE']])
->all();
But this doesn't work.
I only get it to work with one value for m.brand.
So:
$query = Car::getCar($lang)
->where(['m.brand' => 'BMW'])
->all();
Works just fine.
Tried to put in a few other ways, but I don't get this to work.
Does anyone know what I'm doing wrong?
EDIT
The getCar method returns something like:
(new Query())->select(['a.auto_id'])->from('auto_new a')
EDIT 2
Got it to work with:
$query->andWhere(['or', ['m.brand' => 'BMW'], ['m.brand' => 'DODGE']])
You can actually simplify it a lot by using an array with the values you need:
$query = Car::getCar($lang)
->where(['m.brand' => ['BMW', 'DODGE']])
->all();
This will execute with something like WHERE m.brand IN ('BMW', 'DODGE') which returns the result you are looking for.
If I understand you well, you could use something like this:
Model::find()
->orWhere(['brand' => 'brand1'])
->orWhere(['id' => 'brand2'])
->all();
where() can take an array to create sql along the lines of
SELECT * FROM car WHERE brand in ('brand1', 'brand2');
using this construct you can generate an array of brands you wish to return then use the following ActiveQuery.
$brands = ['BMW', 'DODGE'];
$query = Car::find()->where(['brand' => $brands])->all();
On my models I try to write a php model that will get me a associative array from a database. But I don't quite know how to approach this.
So after I execute this SQL query:
SELECT balance_events.weight,balance_events.added_date,
balance_entries.mid FROM balance_events, balance_entries
WHERE balance_entries.added_date BETWEEN '2016-08-02' AND '2016-08-03'
AND balance_entries.ptid =12
AND balance_entries.beid = balance_events.id
I will get this table:
And from that table I want to extract a asociative array that it will look like this:
count = ['13'=>1, '6'=>4, '16'=>3, '4'=>3]
where 'mid'=>number of how many times that mid can be found in the table.
ex. mid '13'=>1 cause you can found it only once.
I think that I will have to use SQL COUNT function, but how I can aggregate all of this in a PHP model in codeigniter? I know how to configure controller and view, but I don't know how to actually do the actual php model that will get me the desired array.
Try this query may help you ,
$result = $this->db->select('balance_events.weight,balance_events.added_date,COUNT(balance_entries.mid) as mid_count')
->from('balance_events, balance_entries')
->where('balance_entries.added_date BETWEEN "2016-08-02" AND "2016-08-03" ')
->where('balance_entries.ptid','12')
->where('balance_entries.beid','balance_events.id')
->group_by('balance_entries.mid')
->get();
return $result->result_array();
I'm not sure how you would create this in SQL but since you tagged php, I wrote a function that would do just this.
<?php
$query = array(array("mid"=>13), array("mid"=>2), array("mid"=>13), array("mid" =>6), array("mid" => 13), array("mid" => 6));
function createMidArray($queryResult){
$returnArray = array();
foreach ($queryResult as $qr){
$returnArray[$qr['mid']]++;
}
return $returnArray;
}
print_r(createMidArray($query));
?>
The output of this was Array ( [13] => 3 [2] => 1 [6] => 2 ) which matches up to my inputted $query (which is a 2D array). I'm expecting the output of your query is stored in a similar array, but with more data and keys
I have a findByAttributes in yii and I was wondering how you output all of the data that meets the criteria specified
I have an example below:
Assuming that in my Test table I have 3 rows which has the value 1 in test1 attribute then I have this code in my view
$a= Test::model()->findByAttributes(array('test1'=> '1'));
$b= $a-> id;
print_r($b);
I've noticed that this code would print the id '1' instead of '1 2 3'.
What code can I use so that it would output ALL of the ids with 1 in their test1 attribute?
sorry for the beginner question. I hope anyone can help...
If you want to get all records you have to use method findAllByAttributes (http://www.yiiframework.com/doc/api/1.1/CActiveRecord#findAllByAttributes-detail) instead of findByAttributes. Method findAllByAttributes will return all rows which meets requirements, then you should iterate over it to get an id.
Example,
foreach( $models as $model) {
print_r($model->id);
}
But if you want to get only ids it is better tou use CDbCommand and querycolumn
Yii::app()->db
->createCommand()
->select('id')
->from('Test')
->where('test1=:value', array(':value'=> 1))
->queryColumn()
It will return an array of ids
For retrive all the rows the meet a specific criteria you can use
findAllByAttributes();
And for obtain all the result you must loop eg ever this result:
$a= Test::model()->findAllByAttributes(array('test1'=> '1'));
foreach($a as $key => $value) {
echo $value->id
}
My dataset is complete in the DB; however I want to create a new field on each of the documents in the db. This new field I want to be derived by some of my input along with other fields that are currently in the database:
IE:
Document:
{
"_id":myId,
"city":"fooville",
"state":"bar"
}
Then I want to take and iterate through every entry and add something like this:
Document:
{
"_id":myId,
"city":"fooville",
"state":"bar",
"cityState":"fooville, bar"
}
Is there an easy way to do this? Trying to avoid re-inserting the entire dataset.
Thank you in advance for your help
(Mongo is awesome)
Something like this:
$results = $collection->find();
// iterate through the results
foreach ($results as $results)
{
$collection->update(array("_id" => new MongoId($result['_id'])),
array('$set' => array("cityState" => sprintf("%s, %s", $result['city'], $result['state']))));
}
I haven't tested it....but it should work...