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!
Related
I am getting an error while inserting into my database.
Its showing column ARRAY. How to fix it? Instead of that I want to pass all dates (showing in the screenshot only dates in the date column)
I want to know in code where I did mistake. Why the array is coming like this?
PHP MODAL
$data_jobschedule = array(
'jobschedule_id' => $jobschedule_id,
'Activity_area_id' => $Activity_area_id,
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq'),
'job_schedule_dates' => $this->input->post('getschedule'),
//'job_schedule_frequency' => $this->input->post('getjob_schedule_frequency'),
'created_at' =>$created_Dt
);
$insert_id = 0;
if ($this->db->insert("activity_area", $data)) { //AM INSERTING ANOTHER RECORD ALSO TO DIFFERENT TABLE
$this->db->insert('job_schedule', $data_jobschedule); //HERE IS THE TABLE I NEED TO ADD DATES AND FREQUENCY
$insert_id = $this->db->insert_id();
}
so your post data is an array, you need looping through it.
on your php model, try change this
$data_jobschedule = array(
'jobschedule_id' => $jobschedule_id,
'Activity_area_id' => $Activity_area_id,
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq'),
'job_schedule_dates' => $this->input->post('getschedule'),
//'job_schedule_frequency' => $this->input->post('getjob_schedule_frequency'),
'created_at' =>$created_Dt
);
$insert_id = 0;
if ($this->db->insert("activity_area", $data)) { //AM INSERTING ANOTHER RECORD ALSO TO DIFFERENT TABLE
$this->db->insert('job_schedule', $data_jobschedule); //HERE IS THE TABLE I NEED TO ADD DATES AND FREQUENCY
$insert_id = $this->db->insert_id();
}
to
$insert_id = 0;
if ($this->db->insert("activity_area", $data)) { //AM INSERTING ANOTHER RECORD ALSO TO DIFFERENT TABLE
if (is_array($this->input->post('getschedule'))) {
foreach($this->input->post('getschedule') as $value) {
$this->db->insert('job_schedule', array(
'jobschedule_id' => $jobschedule_id,
'Activity_area_id' => $Activity_area_id,
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq'),
'job_schedule_dates' => $value[0], //assume array form like your screenshot
'job_schedule_frequency' => $value[1],
'created_at' =>$created_Dt
));
}
$insert_id = $this->db->insert_id();
}
}
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');
My first post on stack after all these years of learning :) So much to thank this community. But anyway...
I'm trying to add new column names to a database dynamically based on what my array will hold. The array's data is unknown/can change, otherwise I'd set it all manually in mysql.
So far, I can get the ALTER TABLE to add a single column entry with this code, but I can't get the foreach loop to iterate through the array for the others following. Surely you can do this I presume?
$test_prod = [
['name' => 'sunny', 'was' => 111, 'now' => 222,],
['name' => 'moon', 'was' => 333, 'now' => 444,],
['name' => 'eclipse', 'was' => 555, 'now' => 666,]
];
foreach ($test_prod as $v) {
$t = $v['name'];
$column_name = $conn->real_escape_string($t);
$update = mysqli_query($conn, "ALTER TABLE table ADD $column_name VARCHAR(255)") or die(mysql_error());
return $update;
}
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 am using codeigniter to produce a left join of two tables, but need to remove the brackets that active record applies to the table name. you know SELECT blah FROM ('some table') I really need these brackets to disappear.
here is my input array:
$retrieve_arr = array(
'table' => 'entries',
'select' => array('entries.entry_id', 'entries.score', 'sc_users.name', 'clients.name'),
'joins' => array(
'clients' => 'entries.client_id = clients.client_id',
'sc_users' => 'entries.sc_user_id = sc_users.sc_user_id'
),
'joinType' => 'left',
'where' => 'null'
);
here is my model:
$retrieve = new Data();
if($get_arr['select'] != 'null')
{
$query = $retrieve->db->select($get_arr['select']);
}
foreach($get_arr['joins'] as $additional => $value)
{
$retrieve->db->join($additional, $value, $get_arr['joinType']);
}
if($get_arr['where'] != 'null')
{
foreach ($get_arr['where'] as $name => $value)
{
$retrieve->db->where($name, $value);
}
}
$query = $retrieve->db->get($get_arr['table']);
$queryData = $query->result_array();
return $queryData;
and here is what my query string:
SELECT `entries`.`entry_id`, `entries`.`score`, `sc_users`.`name`, `clients`.`name` FROM (`entries`) LEFT JOIN `sc_users` ON `entries`.`sc_user_id` = `sc_users`.`sc_user_id` LEFT JOIN `clients` ON `sc_users`.`client_id` = `clients`.`client_id`Array
I have been looking for this for a while so your help is very much appreciated.
If you are referring to the ` backticks, in the Select() portion, use a FALSE as the second parameter (refer to the Users Guide for more info)