I have a model in my laravel appication which uses a table which is re-created each day with a new table name that includes todays date.
I am trying to set the protected $table property in the model to
protected $table = "probe_request_" . $this->getDate;
This is how I have defined the getDate function
private function getDate()
{
return Carbon::now('Europe/London')->startOfDay()->format('d_m_Y');
}
I keep receiving the following error "<strong>Zend compile error</strong>: Constant expression contains invalid operations in <strong>/var/www/intelli_sense/app/sprinkles/geo-sense/src/Database/Models/ProbeRequest.php</strong> on line <strong>23</strong>"
Is there a way I can set the table name with todays date in it? I feel like there must be an easy way to do this that I have missed.
You can't use expressions while creating a field value, but you can override it inside the model constructor:
public function __construct(array $attributes = [])
{
$this->table = "probe_request_" . Carbon::now('Europe/London')->startOfDay()->format('d_m_Y');
parent::__construct($attributes);
}
You can set the new table name like this.
$ProbeRequest= new ProbeRequest;
$ProbeRequest->setTable("probe_request_" . $this->getDate);
Related
I'm not able get the timestamps with dateformat 'U' working in lumen.
In migration:
$table->timestamps();
In Model:
protected $dateFormat = 'U';
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
public function getDateFormat()
{
return 'U';
}
Insert row from controller:
$model = new ApiKey;
$model->random= rand();
$model->name = $name;
$model->scope = $scope;
$model->save();
It does insert the row in the database but with 0000-00-00 00:00:00 values for created_at and updated_at columns.
Also, while retrieving a model via toArray or toJson it thrown exception:
I want lumen to autoupdate the timestamps and retrive timestamps as unixtimestamp format i.e. number of seconds from 1st Jan 1970.
Also, $table->timestamps() didn't create deleted_at column. What do I need to do get this column created via laravel.
Is there any other option than $table->timestamp('deleted_at');?
I've found a solution bay changing timestamps columns to int. But I want the things to be done in laravel way.
Unix timestamps are integers, not compatible with SQL datetime/timestamp fields. If you want to use unix timestamps, use integer field types for storage.
The timestamps() method only creates created_at and updated_at, soft deletes are not enabled by default. This method should not be used if you want integer storage.
If you only want to change the output format when serializing data, use casting:
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'created_at' => 'datetime:U',
];
This is likely caused by the fact that Laravel/Lumen created the date/time columns as the type timestamp not int so you're trying to save wrong type of data in the field, causing the 0000-00-00 00:00:00.
This would also cause the carbon issue as you are trying to createFromFormat with the wrong format compared to the content.
You can use $table->integer('deleted_at'); in your migration to create a deleted_at column.
TL;DR:
Manually create your date time columns with $table->integer('updated_at').
<?php
namespace App\Traits;
use Illuminate\Support\Carbon;
trait sqlServerDateFormat
{
public function fromDateTime($value)
{
return Carbon::parse(parent::fromDateTime($value))->format('d-m-Y H:i:s');
}
}
I have 2 related tables and I need to filter the date of a table by month
My first table have the following fields: Id_agendamien_persona , Id_agendamiento, id_persona
The second table have the following fields: Id_agendamiento, fecha
so I need to filter fecha in the second table,
Mi controller
public function listar(){
$contactos = Contacto::pluck('completo','id_contacto');
$contacto_x_agendamientos = Contacto_x_Agendamiento::all();
array_add($contactos,0,"::Seleccione::");
return view('agendamiento.listar')->with(compact('contacto_x_agendamientos','contactos'));
}
My model
first table
class Contacto_x_Agendamiento extends Model
{
protected $table = "contacto_x_agendamiento";
protected $primaryKey = 'id_contacto_x_agendamiento';
const CREATED_AT = 'fecha_creado';
const UPDATED_AT = 'fecha_modificado';
public function Agendamiento(){
return $this->hasOne(Agendamiento::class,'id_agendamiento','id_agendamiento');
}
}
second table
class Agendamiento extends Model
{
protected $table = "agendamiento";
protected $primaryKey = 'id_agendamiento';
const CREATED_AT = 'fecha_creado';
const UPDATED_AT = 'fecha_modificado';
public function scopeMes($query){
return $query->whereMonth('fecha_agendar','=',date('m'))->get();
}
}
View
<td>{{$contacto_x_agendamiento->Agendamiento->Mes()->fecha_agendar}}</td>
error
Property [fecha_agendar] does not exist on this collection instance.
The issue here, is that you're trying to fetch the property of an Agendamiento model from a Collection that you're getting back as a result.
Here you have two choices. You either get just one model, by using ->first():
echo $contacto_x_agendamiento->Agendamiento->Mes()->first()->fecha_agendar;
Or you iterate the Collection and print each fecha_agendar property:
foreach ($contacto_x_agendamiento->Agendamiento->Mes()->get() as $agendamiento) {
echo $agendamiento->fecha_agendar;
}
On a side note, you should totally rethink your coding style/conventions. I'm fully aware it works, but having id_contacto_x_agendamiento as a primary id or a class name like Contacto_x_Agendamiento isn't best practice.
Having a mix of English and Spanish in classes/properties/variables could also be avoided, to improve other people's readability.
I was working on an old database which primarykey is 'Id'. Eloquent set up the primary key to default 'id', so it is little change, but still can be confusing. Of course I didnt notice that, and I wanted to save updated models to database. There was no error, and $model->save() return was good but database didn't update. Furthermore I have other functions that get models from the database, and they work as they should without overriding $primarykey.
So here is my question: Why isn't eloquent returning any warnings or errors ? Of course I found in the documentation that I should override $primarykey in the model, and then everything worked perfectly.
I was using MySql 10.1.16-MariaDB.
Here is Laravel controller
public function update(Request $request, Order $order)
{
$order->fill($request->get('data'));
$order->save();
$order->products;
return $order;
}
Vue.js function
editOrder () {
this.fullscreenLoading = true
axios.put('/web/' + this.url + '/' + this.rowId, {'data': this.row})
.then(({data}) => {
this.row = data;
this.fullscreenLoading = false
});
},
Laravel Model was standard, of course my model is now properly updated, when i got this problem there was no $primarykey, I didnt mention $fillable and relationship to products but in my project they are defined and working.
class Order extends Model
{
use LogsActivity;
protected $table = 'orders';
protected $primaryKey = 'Id';
protected $fillable = []
}
If you execute the query with get(), create() or similar method, it will work as before because Eloquent doesn't use PK in this case. But some methods like find() will not work for you until you setup $primaryKey property in the model.
You didn't get an error because there was no error.
When you ran $order->save(), the query generated would have been something like:
update `orders` set `field1` = ?, `fieldN` = ?, `updated_at` = ? where `id` is null
This is a perfectly valid SQL statement, and when it runs, it would produce no errors. However, it will also not update any records (unless you do have a record where the id is null).
The reason why the update query is using null is because your Order model does not have an id attribute, it has an Id attribute, and PHP array keys are case-sensitive. So, when Laravel attempts to get the value for the id attribute, it returns null, and uses that in the query.
I have a table with rows with column contain string "this\dIs\dA\dString"
$callPlans = CustomerCallPlan::where('customer_id', $customer->id)->get();
I get the values like above and expected string 'thisXIsXAXString'
as you guess I replace '\d' with 'X'. to do this I use method below inside model class.
class CustomerCallPlan extends Model
{
protected $table = 'customer_callplan';
protected $fillable = [
'template',
'priority',
'customer_id',
'strip',
'add_number',
'actiontype',
'data'
];
public function getNumbertemplateAttribute() {
return str_replace('\d', 'X', $this->attributes['template']);
}
}
But somehow data comes to model without replaced.. what might be cause this ??
This is called an accessor and it'll automatically be called by Eloquent when attempting to retrieve the value. The method name should be the camel cased name of the column you wish to access, prepended by get and followed by Attribute, for example getColumnNameAttribute() will take the column colum_name.
How does loadByCode() works? I have been adding a module to my new project and don't know how to use model uses loadByCode method with a given code.
When you look at magento model class it extends Mage_Core_Model_Abstract which intern extends Varien_Object.
The class Mage_Core_Model_Abstract has function like getId(), load(), save(), delete() etc...
Mysql4 resource files are used to perform database queries on tables.
Suppose we have the file Keyur_Test_Model_Mysql4_Test resource file.
<?php
class Keyur_Test_Model_Mysql4_Test extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init('test/test', 'test_id');
}
public function loadByField($field,$value){
$table = $this->getMainTable();
$where = $this->_getReadAdapter()->quoteInto("$field = ?", $value);
$select = $this->_getReadAdapter()->select()->from($table,array('test_id'))->where($where);
$id = $this->_getReadAdapter()->fetchOne($sql);
return $id;
}
}
And here is the model file Keyur_Test_Model_Test
<?php
class Keyur_Test_Model_Test extends Mage_Core_Model_Abstract
{
public function _construct()
{
parent::_construct();
$this->_init('test/test');
}
public function loadByField($field,$value){
$id = $this->getResource()->loadByField($field,$value);
$this->load($id);
}
}
In this file there are many new functions which have been used. Let’s take them one by one. In our model file, we have used this function -
$id = $this->getResource()->loadByField($field,$value);
$this->getResource() function returns the resource model’s object. So we are simply calling the loadyByField($field,$value) function in the resource model.
getTable() function
Now in our Mysql4 file, in the loadByField() function we have used $table = $this->getMainTable(); .This function returns the table name of the current model, i.e the one defined in the class’s constructor. If you want to get table name of another sql table in magento, we need to the getTable() call e.g
$table = $this->getTable(‘newsletter/subscribe’);
_getReadAdapter() function
Next we have:
$where = $this->_getReadAdapter()->quoteInto(“$field = ?”, $value);
Here the first function too see is the $this->_getReadAdapter() function. This function return an object which has function to perform database query, like fetch(), fetchAll(), query(), etc.
_quoteInfo() function
Another function we have used is quoteInto(): This function is used to create our where conditions.
In this the actual value is substituted into the question mark we have written. For e.g $this->_getReadAdapter()->quoteInto(“user_id = ?”, 3); translates to “user_id = 3″.
Another frequently used variation of quoteInfo() is
$where = $this->_getReadAdapter()->quoteInto("$field IN(?)", array(1,2,3));
this translates to “field in (1,2,3)”
Getting deeper into the quoteInto() function: If we have multiple where conditions we can use
$where = $this->_getReadAdapter()->quoteInto("$field = ? AND ", $value).$this->_getReadAdapter()->quoteInto("$field1 = ? OR ", $value1).$this->_getReadAdapter()->quoteInto("$field2 = ?", $value2);
Continuing on the loadByField function in our resource model, next we have
$select = $this->_getReadAdapter()->select()->from($table,array(‘test_id’))->where($where);
Here we have created the select query using the select(), and on that called the from() function.
from() function
The from() function takes many different parameters, if you want to fire a simple select * query, you need to only pass the table name like from($table).
But right now, I wanted to select just a single column that is test_id, so I passed an array with column name to
select. i.e array(‘test_id’).
If we want to select multiple column, we need to array(‘test_id’,’col1’,’col2’).
This will create a sql like “select test_id,col1,col2 from $table”.
But support we want a sql query like “select test_id as id,col1 as column1 from $table” , i would call -
from($table,array('id'=>'test_id','column1'=>'col1'));