I have a many to many relationship between two tables: atentions and procedimientos. it looks like this
As you can see, my pivot table has 2 extra columns, cantidad, and descuento, along with the keys from both tables.
However, when i try to insert data in that table, i get the error message ErrorException
Array to string conversion and if i format those values using json_encode, i get the following
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '["1","1"]' for column `dentalg`.`atencion_procedimientos`.`cantidad` at row 1 (SQL: insert into `atencion_procedimientos` (`atencion_id`, `cantidad`, `created_at`, `descuento`, `procedimientos_id`, `updated_at`) values (11, ["1","1"], 2020-05-06 02:19:20, ["1","1"], 1, 2020-05-06 02:19:20), (11, ["1","1"], 2020-05-06 02:19:20, ["1","1"], 2, 2020-05-06 02:19:20))
This is my store function
public function store(Request $request)
{
//
$this->validate($request,[
'asunto' => 'required',
'cantidad' => 'required',
'descuento' => 'required',
'total_pago' => 'required'
]);
if(Auth::user()->role_id ==1 or Auth::user()->role_id==2){
$atencion = new Atencion();
$atencion->doctor_id = Auth::id();
$atencion->pacientes_id = $request->paciente_id;
$atencion->asunto = $request->asunto;
$atencion->tipo_pago = 0; //Tratar de Modificar
$atencion->estado_pago = 0;
$atencion->observaciones = $request->observaciones;
$atencion->total = $request->total_pago;
$atencion->save();
$atencion->procedimientos()->attach($request->procedimientos_id,[
'cantidad' => $request->cantidad,
'descuento' => $request->cantidad,
]);
Toastr::success('Tratamiento añadido con éxito','success');
return redirect()->route('admin.Atenciones.index');
} else {
Toastr::error('You are not authorized to do this operation','Error');
return redirect()->back();
}
Models
public function procedimientos(){
return $this->belongsToMany('App\Procedimientos')->withPivot('cantidad', 'descuento')->withTimestamps();
}
and
public function atenciones(){
return $this->belongsToMany('App\Atencion')->withPivot('cantidad', 'descuento')->withTimestamps();
}
Related
Array to string conversion
(SQL)
`insert into `group_members` (`id`, `group_id`, `alias`) values (1, 20, Lilian Marvin PhD)`
$users = User::where('role_id','=',3)->select('id','display_name')->get();
foreach ($users as $user) {
$groups = Group::select('id')->get()->toArray();
// echo $user->display_name ." " .$user->id ."<br/>";
DB::table('group_members')->insert([
'id' => $user->id,
'group_id' => array_random($groups),
'alias' => $user->display_name
]);
}
in the array_random, I believe there's an error
You are trying to save array in group_id column. You need to save only id not array
try this
DB::table('group_members')->insert([
'id' => $user->id,
'group_id' => array_random($groups)['id'],
'alias' => $user->display_name
]);
If you want to get any one of the group then you can try
array_random($groups, 1),
if you want to store multiple, then you may like to convert it to json
json_encode(array_random($groups, 1)),
used laravel helper method Arr::random
The Arr::random method returns a random value from an array
use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$random = Arr::random($array);
// 2 - (retrieved randomly)
i'm new on laravel, basically when i using codeigniter this code works fine.
The problem is i cannot use this for insert data.
for($count = 0; $count < sizeof($cid); $count++){
inset to table for item 1,
inset to table for item 2,
inset to table for item 3,
}
this is my controller
$request->validate([
'pembelian_kode' => 'required',
'barang_kode' => 'required',
'pembelian_total' => 'required',
'pembelian_qty' => 'required',
'supplier_id' => 'required',
]);
$cid = Input::POST('cid');
$cg = PembelianModel::create($request->all());
if($cg){
for($count = 0; $count < sizeof($cid); $count++){
DB::table('pembelian_details')->insert([
'pembelian_kode' => $request['pembelian_kode'], 'barang_kode' => $request['barang_kode'], 'pd_qty' => $request['pembelian_qty']]
);
}
}
return redirect()->route('pembelians.index')
->with('success','Data berhasil ditambah');
reults error
Array to string conversion (SQL: insert into `pembelian_details` (`pembelian_kode`, `barang_kode`, `pd_qty`) values (PBL1812025877, BRG10181125230, 10))
so i have two tables 1 is 'orders' and also 'order_details'. For the table orders it has been successful in adding data, but for orders details there are still errors.
can someone help me ?
I just modified your script .Hope this will work
Problems:
$request['barang_kode']
Missing index
$request is an object not array
$cid = $request->cid;
$cg = PembelianModel::create($request->all());
if($cg){
for($count = 0; $count < count($cid); $count++){
DB::table('pembelian_details')->insert([
'pembelian_kode' => $request->pembelian_kode[$count],
'barang_kode' => $request->barang_kode[$count],
'pd_qty' => $request->pembelian_qty[$count]
]
);
}
}
return redirect()->route('pembelians.index')
->with('success','Data berhasil ditambah');
I'm attempting to create a CitySeeder using Phinx. But I'm getting the following error:
[PDOException]
SQLSTATE[22003]: Numeric value out of range: 1416 Cannot get geometry object from data you send to the GEOMETRY field
Here is my seeders/CitySeeder.php class. The geo_coords field uses a POINT datatype:
<?php
use Phinx\Seed\AbstractSeed;
class CitySeeder extends AbstractSeed
{
public function run()
{
$data = [
[
'name' => 'birmingham',
'geo_coords' => 'POINT(0 0)'
],
[
'name' => 'london',
'geo_coords' => 'POINT(0 0)'
],
[
'name' => 'liverpool',
'geo_coords' => 'POINT(0 0)'
],
[
'name' => 'manchester',
'geo_coords' => 'POINT(40 -100)'
],
];
$cityTable = $this->table('city');
$cityTable->insert($data)->save();
}
}
Which is strange because if I enter that manually into the database it works.
Does the longitude/latitude have to be formatted in a certain way? I've tried using an array, and a space separated long lat format but I still get the same error. I've even went as far as looking through the source code but can not find anything useful.
Any help would be much appreciated.
Edit
I've inspected the code from the Phinx library where the error is happening:
public function insert(Table $table, $row)
{
$this->startCommandTimer();
$this->writeCommand('insert', array($table->getName()));
$sql = sprintf(
"INSERT INTO %s ",
$this->quoteTableName($table->getName())
);
$columns = array_keys($row);
$sql .= "(". implode(', ', array_map(array($this, 'quoteColumnName'), $columns)) . ")";
$sql .= " VALUES (" . implode(', ', array_fill(0, count($columns), '?')) . ")";
$stmt = $this->getConnection()->prepare($sql);
$stmt->execute(array_values($row));
$this->endCommandTimer();
}
The data from array_values($sql) at the point of failure is:
array(2) {
[0]=>
string(10) "birmingham"
[1]=>
string(26) "POINT(0 0)"
}
And the query after $sql is set:
string(55) "INSERT INTO `city` (`name`, `geo_coords`) VALUES (?, ?)"
When doing the following after prepare(): die(var_dump($stmt->debugDumpParams()));:
SQL: [55] INSERT INTO `city` (`name`, `geo_coords`) VALUES (?, ?)
Params: 0
NULL
Logging the MySQL queries shows the following:
2016-12-12T12:53:12.721287Z 12 Query INSERT INTO `city` (`name`, `geo_coords`) VALUES ('birmingham', 'POINT(0, 0)')
I believe this is incorrect because the POINT is being inserted as a string?
Solved the problem using the following:
<?php
use Phinx\Seed\AbstractSeed;
class CitySeeder extends AbstractSeed
{
public function run()
{
$data = [
[
'name' => 'birmingham',
'geo_coords' => [0, 0],
],
[
'name' => 'london',
'geo_coords' => [0, 0],
],
[
'name' => 'liverpool',
'geo_coords' => [0, 0],
],
[
'name' => 'manchester',
'geo_coords' => [0, 0],
],
];
$conn = $this->getAdapter()->getConnection();
$sth = $conn->prepare('INSERT INTO city (`name`, `geo_coords`) VALUES (?, POINT(?, ?))');
foreach($data as $key => $val)
{
$sth->execute([
$val['name'],
$val['geo_coords'][0],
$val['geo_coords'][1]]
);
}
}
}
I'm having trouble updating and creating related records depending on if they exist or not. I want to update the ingredient if they exist, if not insert the ingredient into the database and relate it to the current meal.
public function update($id)
{
$meal = Meal::find($id);
$meal->name = Input::get('name');
// create ingredients
$ingredients = Input::get('ingredient');
$meal_ingredients = array();
foreach($ingredients as $ingredient)
{
$meal_ingredients[] = new Ingredient(array(
'name' => $ingredient['name'],
'unit' => $ingredient['unit'],
'quantity' => $ingredient['quantity']
));
}
//save into the DB
$meal->save();
$meal->ingredients()->saveMany($meal_ingredients);
// redirect
Flash::success('Votre repas a bien été mis à jour!');
return Redirect::to('/meals');
}
Step 1 : Get Meal
$meal = Meal::find($id);
Step 2 : Get Ingredients of Meal (create relation for this)
$ingredients = $meal->ingredients;
Step 3 : Compare Input to current and add does not exist
$new_ingredients = array();
foreach($ingredients as $ingredient)
{
if(!in_array($ingredient->toArray(), Input::get('ingredient')) {
$new_ingredients[] = new Ingredient(array(
'name' => $ingredient['name'],
'unit' => $ingredient['unit'],
'quantity' => $ingredient['quantity']
));
}
}
Step 4 Update
$meal->ingredients->saveMany($new_ingredients);
Ensure you got the relation between meal and ingredient correctly
You can use the firstOrNew() method. You pass it an array of data, and it will return the first record that matches that data, or if no record is found, a new instance of the class with the searched fields already set.
foreach($ingredients as $ingredient)
{
$meal_ingredients[] = Ingredient::firstOrNew(array(
'name' => $ingredient['name'],
))->fill(array(
'unit' => $ingredient['unit'],
'quantity' => $ingredient['quantity']
));
}
I want to save a recipe like this:
$recipe = new Recipe;
//$recipe->user_id = Auth::user()->id;
$recipe->user_id = 40;
$recipe->title = Input::get('title');
$recipe->short_desc = Input::get('short_desc');
$recipe->prep_time = Input::get('prep_time');
$recipe->status = 0;
$recipe->amount = Input::get('amount');
$recipe->save();
//$recipe->ingredients()->sync(Input::get('ingredients'));
foreach(Input::get('ingredients') as $key => $ingredient) {
$recipe->ingredients()->attach($key,['unit' => $ingredient['unit'], 'amount' => $ingredient['amount']]);
}
//$recipe->ingredients()->attach($ingredients->id,['unit' => $unit, 'amount' => $amount]);
$recipe->categories()->sync(Input::get('categories'));
$recipe->recipesteps()->sync(Input::get('description'));
$recipe->push();
//}
return json_encode($recipe);
Data I input via POSTMAN:
http://monosnap.com/image/K5e44iPt3SRaeNhxZqwduXBfIyOeD9
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'unit' in 'field list' (SQL: insert into `rezepte_ingredients_recipe` (`amount`, `ingredients_id`, `recipe_id`, `unit`) values (100, 0, 13, gr))
So it seems that my foreach doesn't create the "ingredients", it just wants to add them.
How can I create the Ingredient(in the ingredients table) with "ID and "name" and add the meta data to the pivot table (unit and amount) ?
Thanks!
Got it!
foreach(Input::get('ingredients') as $key => $i) {
$ingredient = new Ingredients(array('name' => $i['name'],'unit' => $i['unit']));
$ingredient->save();
$recipe->ingredients()->attach($ingredient->id,['amount' => $i['amount']]);
}
->save() was missing!