I am trying to update the created_at and updated_at column names to my own custom values.
I understand that in order to change the column names I need to replace the const in the Model class for CREATED_AT and UPDATED_AT.
I did this:
const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';
But it seems that whenever I make changes, and it is random, my changes are reverted back to:
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
My questions are two: Is there a better way to achieve this? And, why is this happening?
Looks like you are editing the Model class in vendor folder. When ever you do composer update its possible your changes will get override, therefore its not a good practice.
You have to add those constants in your model class. For example
use Illuminate\Database\Eloquent\Model;
class Test extends Model {
const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';
...
}
Related
How I am trying to use map to store multiple key value properties. the problem I see is that it doesn't let me store existing data, it overrides data everytime I tried to set a new property.
Create VERTEX Person extends V;
CREATE CLASS Person EXTENDS V;
CREATE PROPERTY Person.name STRING (MANDATORY TRUE, MIN 3, MAX 50);
Create VERTEX Person set name="test";
update ( SELECT from Person where name="test") SET mapField=
{"property1":mapField.property1+10};
set property1 into map, and update it, works just fine.
update ( SELECT from Person where name="test") SET mapField=
{"property1":mapField.property1+30};
select from Person;
Set another property "property2", now I loose the property1.
update ( SELECT from Person where name="test") SET mapField=
{"property2":mapField.property2+10};
select from Person;
is ther a way I can retain previous property and make this work still?
Thanks
Hari
This should do the trick:
update ( SELECT from Person where name="test")
SET mapField.property1 = mapField.property1 + 30;
In V 2.2 there was also an UPDATE PUT option, ie.
update ( SELECT from Person where name="test")
PUT mapField = property1, eval('mapField.property1 + 30');
but it's not supported anymore (and it's definitely ugly)
I have a table on Postgres that auto generates UUIDs, when I dd Customer::all(); on Laravel I get an array with "cs_id" => "d0402be5-e1ba-4cb2-a80c-5340b406e2c3" which is fine. When I loop or select one record with the only the cs_id the data it retuns 0,2,5 for the three records currently on the table which is incorrect data.
EDIT:
CREATE TABLE customers
(
cs_id character varying(255) NOT NULL DEFAULT gen_random_uuid(),
CONSTRAINT cs_customers_pkey PRIMARY KEY (cs_id),
}
On laravel
$customerData = Customer::where('cs_id','d0402be5-e1ba-4cb2-a80c-5340b406e2c3')->first();
dd($customerData['cs_id']);
For some reason Eloquent messes up there.
just add a getter and use it whenever you need the cs_id
public function getGuid()
{
return $this->attributes['cs_id'];
}
To use uuids auto-generated by the database, define your model as follows:
class Customer extends Model
{
// rename the id column (optional)
protected $primaryKey = 'cs_id';
// tell Eloquent that your id is not an integer
protected $keyType = 'string';
// do NOT set $incrementing to false
}
Then you can use all Eloquent's methods as you would with classic ids:
$customerData = Customer::findOrFail('d0402be5-e1ba-4cb2-a80c-5340b406e2c3');
Use Customer::findOrFail('d0402be5-e1ba-4cb2-a80c-5340b406e2c3');
to get the record matching that pk.
I'm assuming on top you have use App\Customer;
I am trying to get one query work since morning and not able to get it working I have two tables photographers and reviews please have a look at structure and then I will ask the question at the bottom :
Reviews table :
id int(10) unsigned -> primary key
review text
user_id int(10) unsigned foreign key to users table
user_name varchar(64)
photographer_id int(10) unsigned foreign key to photographers table
Photographers table :
id int(10) unsigned -> primary key
name text
brand text
description text
photo text
logo text
featured varchar(255)
Photographers model :
class Photographer extends Model
{
public function reviews()
{
return $this->hasMany('\App\Review');
}
}
Reviews Model :
class Review extends Model
{
public function photographers()
{
return $this->belongsTo('\App\Photographer');
}
}
My logic to query the records
$response = Photographer::with(['reviews' => function($q)
{
$q->selectRaw('max(id) as id, review, user_id, user_name, photographer_id');
}])
->where('featured', '=', 'Yes')
->get();
The question is : I want to fetch all the photographers who have at least one review in the review table, also I want to fetch only one review which is the most latest, I may have more than one review for a photographer but I want only one.
I would add another relationship method to your Photogrpaher class:
public function latestReview()
{
return $this->hasOne('App\Review')->latest();
}
Then you can call:
Photographer::has('latestReview')->with('latestReview')->get();
Notes:
The latest() method on the query builder is a shortcut for orderBy('created_at', 'desc'). You can override the column it uses by passing an argument - ->latest('updated_at')
The with method loads in the latest review.
The has method only queries photographers that have at least one item of the specified relationship
Have a look at Has Queries in Eloquent. If you want to customise the has query further, the whereHas method would be very useful
If you're interested
You can add query methods to the result of a relationship method. The relationship objects have a query builder object that they pass any methods that do not exist on themselves to, so you can use the relationships as a query builder for that relationship.
The advantage of adding query scopes / parameters within a relationship method on an Eloquent ORM model is that they are :
cacheable (see dynamic properties)
eager/lazy-loadable
has-queryable
What you need is best accomplished by a scoped query on your reviews relation.
Add this to your Review model:
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Eloquent\Model;
class Review extends Model {
public function scopeLatest(Builder $query) {
// note: you can use the timestamp date for the last edited review,
// or use "id" instead. Both should work, but have different uses.
return $query->orderBy("updated_at", "desc")->first();
}
}
Then just query as such:
$photographers = Photographer::has("reviews");
foreach ($photographers as $photographer) {
var_dump($photographer->reviews()->latest());
}
I have a PostgreSQL table
CREATE TABLE reservation_table (
idreservation SERIAL NOT NULL,
entry_datetime TIMESTAMPTZ NOT NULL DEFAULT 'NOW',
start_end_dates DATERANGE NOT NULL ,
property_id INT NOT NULL REFERENCES property_table,
...
)
and a constraint to prevent 2 reservations of the same property on same date
ALTER TABLE ONLY reservation_table
ADD CONSTRAINT reservation_double_booking_constraint
EXCLUDE USING gist
(property_id WITH =, start_end_dates WITH &&)
;
Can I enforce my SQL constraint within my Grails Reservation domain ?
I am considering accessing reservation using a view, to avoid problems with postgresql range in groovy
create view resView as
select idReservation,
lower(start_end_dates) AS startDate,
upper(start_end_dates) AS endDate,
property_id
from reservation_table
Ok , but you specified very minimum information to solve this kind of problem , since i have not understood it fully , i have the following suggestion.
How about using before and after interceptor on grails.
class Reservation {
Date startDate ...
def beforeInterceptor = {
//do some date validation here start data or end date
//for exmaple you might check that we have
//any start date currently existing on db
//by findbyStartDate or endDate
//then reject the reservation or saving of this model
println "validation error here , cancel save"
}
static constraints = {
//do some validation here related to ur constraint
startDate max: new Date()
}
}
let me know anything if u need more help . . .
Actually i have manually entered records in mysql database-using grails but i want to show the date in a coloumn in same table.
Is there any solution for this
here is my controller class
class test {
String company_name
String contact_person
Integer phone_no
String status
String place
String address
static constraints = {
company_name(nullable:false)
contact_person(nullable:false)
phone_no(uinque:true,nullable:false)
status(nullable:false)
place(nullable:false)
address( nullable:false )
}
}
Grails provides automatic timestamps via the "dateCreated" property:
Automatic timestamping
If you define a dateCreated property it will be set to the current
date for you when you create new instances. Likewise, if you define a
lastUpdated property it will be automatically be updated for you
when you change persistent instances.
(From the Grails user guide: Events and auto timestamping)
Have a look at dateCreated and lastUpdated in autoTimestamp property in GORM.