i just want to know that is it possible to display data of $dataprovider independent of any gridview.
Like if the $dataprovider contains value of a particular query result than it will be stored as array in that.
So how can i call only one value from $dataprovider
For example my $dataprovider contains value of all select * from user where status=10
so is it possible just to display $dataprovider->user>name just first record.
Thank you
You can certainly access $dataProvider->models as suggested by scaisEdge and get the single model you need, but that is not very efficient, because it executes the query and retrieves all models only to be discarded later.
You can, however, get access to dataProvider's query object, and with it get the single model you need.
$newQuery = clone $dataProvider->query;
$model = $newQuery->limit(1)->one();
Cloning the query is not necessary if it's ok to modify the dataProvider (if you don't use it anywhere else).
UPDATE:
$this->title = isset($dataProvider->models[0]->name) ? $dataProvider->models[0]->name : 'empty result';
Yes inside a dataProvider you can find the models. These are a collection of model and then if you iterate over this collection you can use the single model data e.g.:
foreach( $dataProvider->models as $myModel){
echo myModel->field1;
echo myModel->filed2:
........ // and so on for all the data you need
}
You can see this Yii2 framework doc for ref
Related
I'm looking for a way to rotate via data in ActiveDataProvider and erase some rows. I have rather peculiar data structure and I can't get precise data I need with ->andFilterWhere
I know it is possible to use SqlDataProvider but I would prefer to get to know a way to be able to do foreach on every row in ActiveDataProvider and just unset those ones I don't need.
I'm not pasting my code - I use rather simple controller and model generated via Gii - so nothing crazy here.
Will be really glad if anyone could point me into the right direction.
You can do something like this:
$dataProvider = new ActiveDataProvider(['query' => $query]);
foreach ($dataProvider->models as $model) {
//your logic
}
ok, I have found an answer, so I thought I'd share.
To still be able to use active dataprovider and make a funky sql query I want the long way - I prepared a prequery which gave me only id's of rows I wanted and then I passed them into normal search query in ActiveDataProvider's search.
$query->andFilterWhere([
'customer_id' => $tempids,
This way what I got was - I limited the main query only to preselected rows.
You may use getModels() and setModels() to modify list of models available in data provider:
$models = $dataProvider->getModels();
foreach ($models as $index => $model) {
if (/* some condition */) {
unset($models[$index]);
}
}
$dataProvider->setModels($models);
But this is inefficient (you're creating unnecessary models) and will does not work correctly with pagination (you may get less records on page than you want, including edge case with empty page). It is better idea to filter records on query level - if you're able to filter them using SQL, you should be able to do this using ActiveQuery. It should be possible to add most conditions using andWhere(), including handling subquery:
$subquery = (new Query())->from(/* ... */)-> // ... rest of conditions
$dataProvider->query->andWhere(['customer_id' => $subquery]);
I want to make a query that gets all the users from table "users" and i need to have only user.id.
$users = User::all();
this will get the whole model User but this is a real performance issue for my app. There is too much data going through.
I need to append some data for each user so i can calculate the working hours.
So the question is how to fetch all users without any other data except $user->id?
$name = DB::table('users')->select('id')->get();
For the certain columns, I think this is best:
$users = User::select('id')->get();
See Documentation.
Use the pluck() method:
$users = User::pluck('id');
The pluck method retrieves all of the values for a given key
Getting all User objects with id only:
$users = User::select('id')->get();
Getting all id as straight int value
According to documentation: https://laravel.com/docs/5.3/queries#selects
Specifying A Select Clause (most efficient)
$users = DB::table('users')->select('id')->get();
Retrieving A Single Column From A Row (but this will process all columns)
$name = DB::table('users')->where('name', 'John')->pluck('name');
I found this in the guide, but have no idea how to implement the same
yii\db\Query::count(); returns the result of a COUNT query. Other
similar methods include sum($q), average($q), max($q), min($q), which
support the so-called aggregational data query. $q parameter is mandatory
for these methods and can be either the column name or expression.
Say for example I have a table name 'billing' with columns:
name amount
charge1 110.00
charge2 510.00
Total - 620.00
How I implement using
yii\db\Query::sum('amount');
I have also tried like
$command = Yii::$app->db->createCommand("SELECT sum(amount) FROM billing");
yii\db\Query::sum($command);
but page generates error.
Thanks.
The first part of code you tried appears to be attempting to use Query Builder. In this case, you must create an instance of a query, set the target table, and then compute the sum:
Via Query Builder
(http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html):
$query = (new \yii\db\Query())->from('billing');
$sum = $query->sum('amount');
echo $sum;
The second part of code you tried appears to be attempting to use Data Access Objects. In this case, you can write raw SQL to query the database, but must use queryOne(), queryAll(), queryColumn(), or queryScalar() to execute the query. queryScalar() is appropriate for an aggregate query such as this one.
Via Data Access Objects
(http://www.yiiframework.com/doc-2.0/guide-db-dao.html):
$command = Yii::$app->db->createCommand("SELECT sum(amount) FROM billing");
$sum = $command->queryScalar();
echo $sum;
Within a model the sum could also be fetched with:
$this->find()->where(...)->sum('column');
You can directly use yii query concept in Search Model
$this->find()->from('billing')->where(['column'=>value])->sum('amount');
OR
$this->find()->where(['column'=>value])->sum('amount');
Outside the Model (Billing is model name)
Billing::find()->where(['column'=>value])->sum('amount');
i hope your model name is Billing
inside Billing model use
$this->find()->sum('amount');
in other models
Billing::find()->sum('amount');
In my application, an action takes some user generated input and uses it to update an entry in the database.
The relevant code resembles the following:
$this->Model->save($data);
$result = $this->Model->findById($id);
The problem is that the contents of $result are outdated. That is, $result contains the record as it was before the save.
I'm assuming that the entry just isn't updated until the function returns. However, I can't do the obvious
$result = $this->Model->save($data);
because this method does not preserve relationships. In this case, the model belongs to another model. I need to be able to get the updated record and the record it belongs to.
See if
$result = $this->Model->findById($id);
is loading from the cache, not the database.
Take a look at:
http://fredericiana.com/2007/09/05/cakephp-delete-cached-models-on-database-change/
http://snook.ca/archives/cakephp/delete_cached_models/
Personally, I've never liked Cake's magic find functions. I find them difficult to add extra conditions/joins/etc to and I much prefer to type a few more lines and get something specific that I can easily adjust.
Sounds in this case like the magic find function is returning from the cache, and you should try a regular find call instead:
$this->Model->save($data);
$result = $this->Model->find('first', array('conditions' => array('id' => $id)));
However, you should try and narrow down your problem and find out exactly what it is for future reference. You could try manually clearing the cache before you do your magic find and see if you get the correct response:
$this->Model->save($data);
Cache::clear();
$result = $this->Model->findById($id);
Another unlikely yet possible option is that your $id variable may not be pointing to the correct model row, and your save might be creating a new one so that when you findById($id) the $id is different to the ID of the row you've just saved/created. In this case, it's worth doing a debug($id) or $this->log('ID is: ' . $id, 'my_test_log'); before and after your safe or at intervals through your code to work out what is happening and where.
I use this code but its not working in cakephp and the code is:
$inserted = $this->get_live->query("INSERT INTO myaccounts (fname) values('test');
After this im using:
$lead_id = $this->get_live->query("SELECT LAST_INSERT_ID()");
It's working, but only one time.
Try this. Lots less typing. In your controller, saving data to your database is as simple as:
public function add() {
$data = "test";
$this->Myaccount->save($data);
// $this->set sends controller variables to the view
$this->set("last", $this->Myaccount->getLastInsertId());
}
You could loop through an array of data to save with foreach, returning the insertId after each, or you could use Cake's saveAll() method.
Myaccount is the Model object associated with your controller. Cake's naming convention requires a table called "myaccounts" to have a model class called "Myaccount" and a controller called "Myaccounts_Controller". The view files will live in /app/views/myaccounts/... and will be named after your controller methods. So, if you have a function add()... method in your controller, your view would be /app/Views/Myaccounts/add.ctp.
The save() method generates the INSERT statement. If the data you want to save is located in $this->data, you can skip passing an argument in; it will save $this->data by default. save() even automagically detects whether to generate an UPDATE or an INSERT statement based on the presence of an id in your data.
As a rule of thumb, if you're using raw sql queries at any point in Cake, you're probably doing it wrong. I've yet to run into a query so monstrously complex that Cake's ORM couldn't model it.
http://book.cakephp.org/2.0/en/models/saving-your-data.html
http://book.cakephp.org/2.0/en/models/additional-methods-and-properties.html?highlight=getlastinsertid
HTH :)
You can get last inserted record id by (works for cakePHP 1.3.x and cakePHP 2.x)
echo $this->ModelName->getLastInsertID();
Alternately, you can use:
echo $this->ModelName->getInsertID();
CakePHP 1.3.x found in cake/libs/model/model.php on line 2775
CakePHP 2.x found in lib/Cake/Model/Model.php on line 3167
Note: This function doesn't work if you run the insert query manually
pr($this->Model->save($data));
id => '1'
id is a last inserted value