$graph_name = T_Graph_Name::find()->all();
$g1_01_short_desc = $graph_name::find()->where(['g_code'=>'g1_01']);
thx for help.
find()->all() return all models of you model (T_Graph_Name)
if you want just some models (eg: filtering the column g_code = 'g1_01') you should use
$models = T_Graph_Name::find()->->where(['g_code'=>'g1_01'])->all();
or
$model = T_Graph_Name::find()->->where(['g_code'=>'g1_01'])->one();
all() return a collection of models so for accessing a column you should use an index or iterate over eg:
foreach($models as $m ){
echo $m->your_column_name;
}
one() retunr just one model so for accessi a column you con use
echo $model->your_column_name;
Related
I have a key value pair that I am inserting into a model with the following:
public function addContactDetail(Request $request){
$data = $request->all();
$contact_id = $data['contact_id'];
$contact = Contact::find($contact_id);
$details = $contact->details;
$details[$data['label']] = $data['value'];
$contact->details = $details;
$contact->save();
return response()->json($contact);
}
After insert it sometimes puts it randomly in the middle of the object. How do I keep it at the end?
If you are using Laravel 5 or greater version,
Try casting your json column into array in eloquent using mutators. like this.
inside your Contact Model
protected $casts = [
'details' => 'array',
];
By doing so, I guess you will get what you want. Try it and let me know
I'm inserting into a table data coming from another table which is basically a subset of the first table.
$partialProduct = partialProducts::find()
->where(['company_id' => $company_id])
->andWhere(['productName' => $productName])->one();
$partialProductData = ($partialProductData['attributes']);
$product = Yii::$app->db->createCommand()
->insert('products', [
'field1' => $field1value,
...
...
'fieldN' => $fieldN,
])->execute();
Something like that could work, but considering that partialProductData has a lot of fields, I was searching for a cleaner way of doing it.
I've tried with a foreach(partialProductData as $key => $value) approach, considering that the keys are named as the products table column names, but I struggled in obtain something viable.
As suggested, creating an array of key/values pairs should work if the keys match the table fields in both models. Something like:
$data = [];
foreach($partialProduct->attributes as $key => $value):
$data[$key] = $value;
endforeach;
$product = Yii::$app->db->createCommand()
->insert('products', $data)
->execute();
Alternatively, you could use massive assignment. Again, for this to work the fields on both models would need to match:
$product = new Product;
$product->attributes = $partialProduct->attributes;
$product->save();
If you only want to save certain fields from your partialProducts to your Product, you can use scenarios to select the specific fields you want to be to set with massive assignment:
In Product.php
const SCENARIO_TEST = 'test';
...
public function scenarios()
{
return [
self::SCENARIO_TEST => ['field_1', 'field_2'], // Any field not listed here will not be set
];
}
And wherever you're doing the save:
$product = new Product;
$product->scenario = Product::SCENARIO_TEST;
$product->attributes = $partialProduct->attributes;
$product->save();
I am looking for a way to retrieve all models in a database. Then loop through all of the models and read out the values for name, firstname and phonenumber.
So far I've gotten this and failed to go past it:
$searchModel = new EmployeeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
I am then looking to implement those three values in a simple HTML table:
<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>
The table should be part of a PDF output, so ideally I would save it to a variable:
$html_table = '<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>';
I would need to get this for every model that fulfills the criteria of status = 'active' in the database.
So far I've only been able to get tables via gridView and not in a HTML template either.
You don't really need a data provider to achieve this, you could simply try :
$models = Employee::find()->where(['status'=>'active'])->orderBy('name ASC')->all();
foreach ($models as $model) {
echo "<tr><td>{$model->firstname}</td><td>{$model->name}</td><td>{$model->phone}</td></tr>";
}
Read more : http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#querying-data
You can get all models like this:
$employees = Employee::find()
->select('firstname, name, phone')
->asArray()
->where(['status'=>'active'])
->all();
This way you will get an array of arrays containing the 3 selected fields, so now you only need to use a foreach to loop through them and create the table:
$html = '<table>';
foreach($employees as $employee) {
$html .= '<tr><td>'.$employee['firstname'].'</td><td>'.$employee['name'].'</td><td>'.$employee['phone'].'</td></tr>';
}
$html .= '</table>'
Is there anyone who knows how to do this without the technique of doing it in a one query string. I mean the popular ways I see on the net is by looping in data(the updates) and generating a single update statement and then fire a query. Is it possible for an Eloquent Approach or DB without looping?
This is posible with Eloquent, it might be necessary to enable mass-assignment, but you will get an error if so.
$post_data = Input::all();
$model = Model::find($id);
$model ->fill($post_data);
$model ->save();
or
$post_data = Input::all();
Model::find($id)->update($post_data);
Yes, you can do that but in that case, you have to make the array of data that is a loop is needed to store the data in the array with respective field_name => value of the table.
The following is the example:
$Array = array(); //This is needed to hold data while looping over $YourData
$YourData - is the array of data you want to store in the respective table.
foreach ($YourData as $YourDatakey => $YourDatavalue ){
$Array = [
'table_column_name' => $YourDatavalue['value_from_array'],
'table_column_name' => $YourDatavalue['value_from_array'],
'table_column_name' => $YourDatavalue['value_from_array'],
...... and so on
];
}
$InsertQuery= YourModelName::create($Array);
PS:
YourModelName model file should have the columns in protected
$fillable = ['column1','column2'....];
You should use App\Models\ModelName; at the top of the file.
Using PDO I have built a succinct object for retrieving rows from a database as a PHP object with the first column value being the name and the second column value being the desired value.
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
I now want to apply it to a function with 2 parameters, the first containing the table and the second containing any where clauses to then produce the same result.
function select($table,$condition){
$sql = "SELECT * FROM `$table`";
if($condition){
$sql .= " WHERE $condition";
}
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
}
The idea that this could be called something like this:
<?php select("options","class = 'apples'");?>
and then be used on page in the same format as the first method.
<?php echo $option['green'];?>
Giving me the value of the column named value that is in the same row as the value called 'green' in the column named field.
The problem of course is that the function will not return the foreach data like that. That is that this bit:
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
cannot return data like that.
Is there a way to make it?
Well, this:
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
Can easily become this:
$sql = "SELECT * FROM `site`";
$site = array();
foreach( $sodb->query($sql) as $row )
{
$site[] = $row;
}
print_r($site);
// or, where 0 is the index you want, etc.
echo $site[0]['name'];
So, you should be able to get a map of all of your columns into the multidimensional array $site.
Also, don't forget to sanitize your inputs before you dump them right into that query. One of the benefits of PDO is using placeholders to protect yourself from malicious users.