Laravel bad query insert - mysql

I have a problem inserting data into my database and always get the following error.
SQLSTATE[22003]: Numeric value out of range: 1416 Cannot get geometry object from data you send to the GEOMETRY field
I tried to insert data with my Eloquent model using query builder, but it gave me the same error. In the migration file I have:
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id')->autoIncrement()->primary();
$table->text("name");
$table->multiLineString("opinion");
$table->string("post");
$table->timestamp("date");
});
I've also tried to insert data with this:
$validatedData = $this->validate($request, [
'name' => 'required|alpha_dash|max:40|min:3',
'opinion' => 'required|alpha_dash|max:40|min:3',
]);
$validatedData = Binput::all();
DB::table("books")->insert([
"name" => $validatedData["name"],
"post" => $url,
"opinion" => $validatedData["opinion"],
]);

I don't know this Binput::all(); came from.
Can you try to delete this line $validatedData = Binput::all();
Should be:
$validatedData = $this->validate($request, [
'name' => 'required|alpha_dash|max:40|min:3',
'opinion' => 'required|alpha_dash|max:40|min:3',
]);
DB::table("books")->insert([
"name" => $validatedData["name"],
"post" => $url,
"opinion" => $validatedData["opinion"],
]);

I solve it by changing the migration instead of string and text i did char and it work
$table->bigIncrements('id')->autoIncrement()->primary();
$table->char("name");
$table->char("opinion");
$table->char("post");
$table->timestamps();
when i tried this migration it work
thank you all

Related

I want to modify array-column output when fetched

This is my data table image
my blade file
#table([
'id' => 'Persons.index',
'xhr' => route('api.manage-dup-api'),
'ns' => 'PersonsIndex',
'columns' => $columns ?? [],
'filters' => $filterTable ?? [],
'params' => [
'filters_live' => false,
'selectable' => true,
'toolbar_style' => 'fixed'
]
])
this is a query which passes data to a data table [API]
$q->with('user')
->with('user.roles')
->select(
'persons.*',
'birth->date as birthdate'
)->`enter code here`whereIn('id', $id)->orWhereIn('old_id_CONINET', $coninet_ids);
return $this->outputList($q, $request);
as shown in the picture I want to remove ["] from the CONINET_ID table
you are storing an array of strings in the DB.
you can convert the array values to int:
array_map('intval', $array);
you can also create an accessor on your eloquent model
public function getOldIdConinetAttribute($value)
{
return array_map('intval', $value);
}
It would better if you give some detailed info. As of now details mentioned above can not explain your code. As of my understanding, I suggest you to check Yajra datatable plugin which will help you solving your issue.
or you can cast coninet_id to array by adding below code in your model.
protected $casts = [
'coninet_id' => 'array'
];

Setting a default value on join table from another table when model is edited or created

Hoping someone may be able to point me in the right direction.
I have a app that consists of (among other things) Recommendations and Assessments. They are joined with a join table that includes extra fields that I would like to update but am struggling to figure out how.
As you can see above, when I create a Reccommendation, I set the following fields:
default_user_impact
default_business_impact
default_deployment_complexity
default_criticality
Now when I create a new Assessment or edit one that has not got any Recommendations linked the Assessment saves fine because nothing is needing to be written to the join table.
When I try to edit an Assessment to include one or more Recommendations, the app tries to write the link to the join table and fails because the user_impact, business_impact, deployment_complexity and criticality fields aren't specified - perfectly normal because I have set the fields to required in MySQL right? The error I get in CakePHP is
SQLSTATE[HY000]: General error: 1364 Field 'user_impact' doesn't have a default value
What I want to be able to do is at the time of editing or creating an Assessment is to use the values in the Recommendations table to populate the corresponding join table entries. Any ideas how to go about this?
So as an example:
user_impact = default_user_impact
business_impact = default_business_impact
deployment_complexity = default_deployment_complexity
criticality = default_criticality
The reason I want to do this is so that I can have the Recommendations set with values for those fields, and then if a user wants to run an assessment and they want to adjust the values just for their own assessment then it won't impact others etc.
Here is my AssessmentsTable association.
$this->belongsToMany('Recommendations', [
'foreignKey' => 'assessment_id',
'targetForeignKey' => 'recommendation_id',
'joinTable' => 'assessments_recommendations',
'through' => 'assessments_recommendations',
]);
Here is my RecommendationsTable association.
$this->belongsToMany('Assessments', [
'foreignKey' => 'recommendation_id',
'targetForeignKey' => 'assessment_id',
'joinTable' => 'assessments_recommendations',
'through' => 'assessments_recommendations',
]);
Here is my AssessmentsRecommendations association:
$this->belongsTo('Assessments', [
'foreignKey' => 'assessment_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Recommendations', [
'foreignKey' => 'recommendation_id',
'joinType' => 'INNER',
]);
This is what my AssessmentsController edit function looks like:
public function edit($id = null)
{
$assessment = $this->Assessments->get($id, [
'contain' => ['Recommendations'],
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$assessment = $this->Assessments->patchEntity($assessment, $this->request->getData(), ['associated'=>['Recommendations._joinData']]);
if ($this->Assessments->save($assessment, ['associated' => ['Recommendations._joinData']])) {
$this->Flash->success(__('The assessment has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The assessment could not be saved. Please, try again.'));
}
$clients = $this->Assessments->Clients->find('list', ['limit' => 200]);
$recommendations = $this->Assessments->Recommendations->find('list', ['limit' => 200]);
$this->set(compact('assessment', 'clients', 'recommendations'));
}
Now when I've added the beforeSave function to the AssessmentsRecommendationsTable I see the following error:
Argument 2 passed to App\Model\Table\AssessmentsRecommendationsTable::beforeSave() must be an instance of App\Model\Table\EntityInterface, instance of Cake\ORM\Entity given, called in /var/www/html/csa-portal/vendor/cakephp/cakephp/src/Event/EventManager.php on line 310
Any help would be much appreciated.
First, the associations you are using are wrong. It should be like this
For AssessmentsTable
$this->hasMany('AssessmentsRecommendations', [
'foreignKey' => 'assessment_id'
]);
For RecommendationsTable
$this->hasMany('AssessmentsRecommendations', [
'foreignKey' => 'recommendation_id'
]);
For AssessmentsRecommendationsTable
$this->belongsTo('Assessments', [
'foreignKey' => 'assessment_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Recommendations', [
'foreignKey' => 'recommendation_id',
'joinType' => 'INNER',
]);
Now for the default values, you have to user beforeSave in you AssessmentsRecommendationsTable.php file.You can modify your data as per your need here before the save.
public function beforeSave(Event $event, EntityInterface $entity, \ArrayObject $options)
{
if ($entity->isNew()) { // Returns true when you add new record
$recommendation = TableRegistry::getTableLocator()->get('Recommendations')->get($entity->recommendation_id);
$entity->user_impact = $recommendation->default_user_impact;
$entity->business_impact = $recommendation->default_business_impact;
$entity->deployment_complexity = $recommendation->default_deployment_complexity;
$entity->criticality = $recommendation->default_criticality;
}
}
I have never used belongsToMany, if the associations works for you then ignore the association part.
Have you considered writing a Rule to handle this?
https://book.cakephp.org/3/en/orm/validation.html#applying-application-rules

Don't create field in database

I hava code like below. It creates a field in database and show in another places. I would like to block create a database field if message field is not exit. Rest fields are taken from system. What is wrong in my code.
$delivery->comments_buro()->create([
'name' => auth()->user()->firstname,
'user_id' => auth()->user()->id,
'message' => $request['repair_report_buro'],
'icon' => 'fa fa-commenting-o',
'style' => $position->style,
]);
Thanks for help.
You need Laravel Validations for that. Please read this: https://laravel.com/docs/5.8/validation
For example:
//controller
public function index(Request $request)
{
$validator = Validator::make($request->all(), [
'message' => 'required|string',
]);
if ($validator->fails()) {
//do validation error handling here
}
// create new row in database.
}
I have a right code. It works with it. I close this question. The right code is:
if(isset($request['repair_report_buro']) && !empty($request['repair_report_buro'])){
$delivery->comments_buro()->create([
'name' => auth()->user()->firstname,
'user_id' => auth()->user()->id,
'message' => $request['repair_report_buro'],
'icon' => 'fa fa-commenting-o',
'style' => $position->style,
]);
}

yii2: geometry type column in migration table

I'm learning Yii2 framework. There's a geometry type column in my MySQL table. I was wondering if I could create it with a Yii2 migration table. Unfortunately, there is no such geometry() method in yii\db\SchemaBuilderTrait class so I assume the following won't work:
$this->createTable('{{%gps}}', [
...
'gps' => $this->geometry()->notNull()
...
]);
Does anyone know any workaround for this?
I haven't used for create a geometry but you can also use an hash format for create column
use yii\db\Schema;
use yii\db\Migration;
$this->createTable('Your_table ', [
'id' => 'pk',
'user_id' => 'integer not null',
'land_scope_code' => 'string(4)',
'init_lat' => 'decimal(24,20)',
'init_lng' => 'decimal(24,20)',
'init_zoom' => 'integer',
]);
could be this is useful for your
$this->createTable('{{%gps}}', [
...
'gps' => 'geometry not null';
...
]);

How do I best avoid inserting duplicate records in CakePHP?

I'm pulling data from several remote DataSources, restructuring to fit my models schema and finally passing the array to MyModel::saveAll();
I'd like to avoid importing duplicate records (ie, don't import if MyModel.external_id = 120 & MyModel.external_type = 'basecamp.comment' already exists in db).
What's the most efficient way of going about this?
Sample data:
$data['MyModel'] = [
[
'title' => 'foo',
'created' => '2013-12-18 11:29:06',
'external_id' => 120,
'external_type' => 'github.commit'
],
[
'title' => 'bar',
'created' => '2013-12-18 13:22:06',
'external_id' => 120,
'external_type' => 'basecamp.comment'
]
];
NB: Notice that MyModel.external_id isn't unique on it's own.
This is where validation comes into play. In your MyModel class, add the following:
public $validate = array(
'external_type' => array(
'rule' => 'idAndTypeUnique',
'message' => "Type and ID already exist"
)
);
public function idAndTypeUnique()
{
$existing = $this->find('first', array(
'conditions' => array(
'external_id' => $this->data[$this->name]['external_id'],
'external_type' => $this->data[$this->name]['external_type']
)
));
return (count($existing) == 0);
}
Your saveAll() call would look like:
$this->MyModel->saveAll($data, array('validate' => true));
The easiest way is to make a unique index on those two fields.
alter table my_model add unique index(external_id, external_type);
This forces the constraint in the database level.
If you want to force this constraint in the cake layer, then check this out:
cakephp isUnique for 2 fields?