I have a mongoose find method like this,
photo.find({},{
name:1,
src:1,
likes:{$literal:[]},
dislikes:{$literal:[]},
}).then(photos => ....)
what I want is, when I run the code likes and dislikes field must be an empty array for every record.
I try this way but not working.
Unsupported projection option: likes: { $literal: 1 }
Any idea to add default value for any field in find method ?
As per mongoose, document schema is constructed during its creation. So you can also edit the schema with a default value, so for every record, when it is created it will create likes, and dislikes with empty values.
You can also do this way, if you feel the schema control is not in your hands.
https://mongoosejs.com/docs/2.7.x/docs/defaults.html
photo.find({ 'name' : '1', 'likes': {$ne: []}})
I am using ef-core 2.1 with MSSQL, in OnModelCreating I use the following which auto populates a created field correctly:
modelBuilder
.Entity<MyModel>()
.Property(e => e.Created)
.HasDefaultValueSql("GETUTCDATE()")
.ValueGeneratedOnAdd()
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
Additionally, I want to populate (and update thereafter) another field as follows:
modelBuilder
.Entity<MyModel>()
.Property(e => e.Modified)
.HasDefaultValueSql("GETUTCDATE()")
.ValueGeneratedOnUpdate()
.Metadata.ValueGenerated = ValueGenerated.OnUpdate;
However, this has no effect. In reading value-generated-on-add-or-update it is not clear to me if no facility exists to support this and a trigger is the only option or I simply have the configuration wrong.
The fluent method calls appear to support this, anyone know what I am doing wrong?
Hmm, I am not real familiar with what you are trying with .Metadata.ValueGenerated, however, I am doing something very similar in my project with success (note that my db is MySQL).
Maybe try like below.
modelBuilder
.Entity<MyModel>()
.Property(e => e.Modified)
.HasDefaultValueSql("GETUTCDATE()")
.ValueGeneratedOnAddOrUpdate();
I have read and worked with the other posts about this and it appears the version of Laravel 4 I just downloaded has more changes made to the way the JSON input is handled by a controller.
$input = Input::json()->all(); gives me errors as if I am referring to something that does not exist when I request some part of the payload after doing a PUT request. And without ->all(); I get a symfony error.
Does anyone know how to get good JSON from backbone in Laravel 4's latest version?
Currently, I am doing the long way around to get my data, ie:
$input_title = Input::get('title');
$input_completed = Input::get('completed');
$task = Task::find($id);
$task->title = $input_title;
$task->completed = $input_completed;
$task->save();
Yes, I am doing the tutorial on tutsplus to learn laravel/backbone, so a little noob patience is apreciated.
The error I get when using Input::get(); is:
{"error":{"type":"UnexpectedValueException","message":"The Response content must be a string or object implementing __toString(), \"array\" given.","file":"/Users/brentlawson23/Sites/laravel4App/bootstrap/compiled.php","line":16858}}
I really want to get the Laravel-specific answer instead of using straight php to stringify the payload.
I get same error using just Input::json();
For the current beta of Laravel 4, Input::json(); is not getting a stringified version of the request payload that can be used to create a new row in a table, nor does Input::json()->all(); (hoping to play nice with the ParameterBag from symfony). I have tried json_encode among other hacks and basically every step of the way in this tut, I hit some brick wall. Anyone have a suggestion based on what I have presented here?
Today I got this when simply trying to echo the result of $input = Input::json(); :
{"error":{"type":"ErrorException","message":"Catchable Fatal Error: Object of class Symfony\Component\HttpFoundation\ParameterBag could not be converted to string in /Users/brentlawson23/Sites/laravel4App/app/controllers/TasksController.php line 45","file":"/Users/brentlawson23/Sites/laravel4App/app/controllers/TasksController.php","line":45}}
Yes, I have studied the Symfony API.
I had a similar problem. Input from Backbone is converted to array in Laravel. On tutsplus, Jeffrey Way is using object. So I was trying to do this (like in tutorial):
return $input->title // using object,but got an error.
If I change that line to:
return $input["title"] // everything works fine with array.
I'm also working through the Backbone tutorial on tuts+. If I'm right in assuming are you stuck on the Creating New Contacts section? Below is how I got it to work for me, in ContactController.php:
public function store()
{
$input = Input::all();
Contact::create(array(
'first_name' => $input['first_name'],
'last_name' => $input['last_name'],
'email_address' => $input['email_address'],
'description' => $input['description']
));
}
And then also needed to update app/models/Contact.php with the below:
class Contact extends Eloquent {
protected $fillable = array('first_name', 'last_name', 'email_address', 'description');
}
That should get it working for you and insert the contact into the database. If I've misread let me know and I can have another look.
Cheers,
Sean
I've got the following relationship set-up between two models
Story belongsTo StoryType
StoryType hasMany Story
I've set-up a form to select the StoryType for each story using the following code:
echo $this->Form->input('Story.story_type_id', array('tabindex' => 2));
with this code in the controller to populate the list
$this->set('story_types', $this->Story->StoryType->find('list', array ('order' => 'title')));
But it's not populating the select box with anything. I know that the find() option is working because doing a debug within the controller produces this:
Array
(
[1] => First Person
[3] => Third Person
)
The weird thing is that it's exactly the same code, just querying other models, to populate select lists for things like users and genres, it's just the story types that isn't working.
Any ideas? Cheers.
You don't mention which version of CakePHP you're using, but try setting storyTypes rather than story_types:
$this->set( 'storyTypes', $this->Story->StoryType->find( 'list', array( 'order' => 'title' ) ) );
Older versions of CakePHP (pre-1.3) modified set variable names to headlessCamelCase and, even if you're using 1.3.x, there may be a little bit of that infrastructure lingering. It's a bit of a reach, but it's easy enough to test and it seems plausible that this could be the root of your problem.
I'll be curious to see what you find out.
This is a little hacky, but I think it will work:
echo $this->Form->input('Story.story_type_id', array('tabindex' => 2, 'options' => $story_types));
here's what you should really do .. (esp, for version 2.x) - in case if some people are facing the same problem.
[inside your constroller action]
$oneOfTheColumns = 'title'; //just for sake of making it clear - if you have to order the results
$storyTypes = $this->Story->StoryType('find', array('order'=>$oneOfTheColumns));
$this->set(compact('storyTypes'));
[inside your view]
echo $this->Form->input('StoryType');
If I do getLastInsertId() immediately after a save(), it works, but otherwise it does not. This is demonstrated in my controller:
function designpage() {
//to create a form Untitled
$this->Form->saveField('name','Untitled Form');
echo $this->Form->getLastInsertId(); //here it works
}
function insertformname() {
echo $this->Form->getLastInsertId(); //this doesnt echo at all
}
Please suggest a way to get the functionality I want.
CakePHP has two methods for getting the last inserted id: Model::getLastInsertID() and Model::getInsertID().
Actually these methods are identical so it really doesn't matter which method you use.
echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();
This methods can be found in cake/libs/model/model.php on line 2768
Just use:
$this->Model->id;
In Cake, the last insert id is automatically saved in the id property of the model. So if you just inserted a user via the User model, the last insert id could be accessed via $User->id
id - Value of the primary key ID of
the record that this model is
currently pointing to. Automatically
set after database insertions.
Read more about model properties in the CakePHP API Docs: http://api.cakephp.org/2.5/class-AppModel.html
Edit: I just realized that Model::getLastInsertID() is essentially the same thing as Model->id
After looking at your code more closely, it's hard to tell exactly what you're doing with the different functions and where they exist in the grand scheme of things. This may actually be more of a scope issue. Are you trying to access the last insert id in two different requests?
Can you explain the flow of your application and how it relates to your problem?
You'll need to do an insert (or update, I believe) in order for getLastInsertId() to return a value. Could you paste more code?
If you're calling that function from another controller function, you might also be able to use $this->Form->id to get the value that you want.
Try using this code in your model class (perhaps in AppModel):
function get_sql_insert_id() {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->lastInsertId();
}
Caveat emptor: MySql's LAST_INSERT_ID() function only works on tables with an AUTO_INCREMENT field (otherwise it only returns 0). If your primary key does not have the AUTO_INCREMENT attribute, that might be the cause of your problems.
this is best way to find out last inserted id.
$this->ModelName->getInsertID();
other way is using
$this->ModelName->find('first',array('order'=>'id DESC'))
There are several methods to get last inserted primary key id while using save method
$this->loadModel('Model');
$this->Model->save($this->data);
This will return last inserted id of the model current model
$this->Model->getLastInsertId();
$this->Model-> getInsertID();
This will return last inserted id of model with given model name
$this->Model->id;
This will return last inserted id of last loaded model
$this->id;
Try to use this code. try to set it to a variable so you can use it in other functions. :)
$variable = $this->ModelName->getLastInsertId();
in PHP native, try this.
$variable = mysqli_insert_id();
This will return last inserted id of last loaded model
$this->id;
This will return last inserted id of model with given model name
$this->Model->id;
This will return last inserted id of the model current model
CakePHP has two methods for getting the last inserted id:
Model::getLastInsertID() and Model::getInsertID().
echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();
Below are the options:
echo $this->Registration->id;
echo $this->Registration->getInsertID();
echo $this->Registration->getLastInsertId();
Here, you can replace Registration with your model name.
Thanks
Use this one
function designpage() {
//to create a form Untitled
$this->Form->saveField('name','Untitled Form');
echo $this->Form->id; //here it works
}
You can get last inseted id with many ways.Like Model name is User so best way to fetch the last inserted id is
$this->User->id; // For User Model
You can also use Model function but below code will return last inserted id of model with given model name for this example it will return User model data
$this->User->getLastInsertId();
$this->User->getInsertID();
When you use save(), the last insert ID is set to the model’s $id property. So:
if ($this->Model->save()) {
printf('Last insert ID was %s', $this->Model->id);
}
Each time a save method is called on a model, cake internally calls Model::getLastInsertId() and stores the result into model class attribute id, so after calling save() it is not necessary to call Model::getLastInsertId() or inserId(), as tha value can be directly accessed like this
$id = $this->id;// within a model
$id = $this->{$this->modelName}->id;// in a controller
After insertion of data, we can use following code to get recently added record's id:
$last_insert_id=$this->Model->id;
each time you perform an insert operation on any model, cake internally fetchesthe last insert Id and Sets to Model->id attribute.
so one can access it directly by $Model->id;,
no need to query again for lastInsertId.
I think it works with getLastInsertId() if you use InnoDB Tables in your MySQL Database. You also can use $this->Model->id
$Machinedispatch =
$this->Machinedispatch->find('first',array('order'=>array('Machinedispatch.id DESC')));
Simplest way of finding last inserted row. For me getLastInsertId() this not works.
Actually you are using the getLastInsertId or getInsertId in a wrong manner.
getLastInsertId() is meant to work only after save() method.
It will even not work after a manual insert, as cake engine is storing the mysql_insert_id under $this->_insertID inside the save method which can be retrieved via the getLastInsertId or getInsertId.
Now in your case
$this->Model->id
OR
$this->Model->find('first',array('order'=>'id DESC'))
Will do.
This is interesting, I also stumbled upon this issue. What you asked perhaps how to get the last ID of a certain model regardless of it's state, whether it's just been inserted or not. To further understand what getInsertID does, we need to take a look at the source:
Link 1: http://api20.cakephp.org/view_source/model#line-3375
public function getInsertID() {
return $this->_insertID
}
Yup, that's the only piece of code inside that function. It means that cakephp caches any last inserted ID, instead of retrieve it from the database. That's why you get nothing if you use that function when you haven't done any record creation on the model.
I made a small function to get the last ID of a certain table, but please note that this should not be used as a replacement of getLastID() or getLastInsertID(), since it has an entirely different purpose.
Add the function lastID() to the AppModel as shown below so that it can be used system wide. It has it's limit, which can't be used on model with composite primary key.
class AppModel extends Model {
public function lastID() {
$data = $this->find('first',
array(
'order' => array($this->primaryKey . ' DESC'),
'fields' => array($this->primaryKey)
)
);
return $data[$this->name][$this->primaryKey];
}
}
Original Source : Class Model
In CakePHP you can get it by:
Model::getInsertID() //Returns the ID of the last record this model inserted.
Model::getLastInsertID() //Alias to getInsertID().
$this->Model->field('id', null, 'id DESC')