How to insert in Laravel? - laravel

I have output object $product after inserting data into table Product:
$product = Product::create($data);
In model Product I have:
public function images()
{
return $this->hasMany("App\ProductImage");
}
The I try to add images to table product_images:
$product->images()->save(new ProductImage(UploadFiles::$files));
Relationship beetwen tables is product.id = product_images.
So, after inserting I get message:
General error: 1364 Field 'image' doesn't have a default value (SQL: insert into `product_images` (`product_id`) values (21))

OK, firstly let's deal with saving one image:
Assuming you have a product_images table with id, image, product_id, you would attach an image like so:
$image = new ProductImage(['image' => 'myImage.jpg']);
$product->images()->save($image);
Now it looks like you have an array, so you can't save that directly, you need to put it in a for loop. I don't know the format of your UploadFiles::$files, but I'll assume it's just a list of file names to save:
$files = UploadFiles::$files;
foreach($files as $file){
$image = new ProductImage(['image' => $file]);
$product->images()->save($image);
}
Alternatively, you could create the whole thing as an array and use saveMany, which would be better:
$files = UploadFiles::$files;
$productImages = [];
foreach($files as $image){
$productImages[] = new ProductImage(['image' => $image]);
}
$product->images()->saveMany($productImages);

Related

Column value as index to generate 2 level collection

I am trying to get a collection which has index as column values.
First level will have product_id as index and second level will have stock_date.
$data = Model::select('column1', 'product_id', 'stock_date')
->where('some condition')
->get();
$data = collect($data)->groupBy('product_id');
With the code above, I get the collection with product_id as the indexes.
I need the data of each product indexed by stock_date
If, for example, for product_id - 1, I have multiple records, I tried
$product_details = collect($data[1])->groupBy('stock_date');
But it does not index the records with stock_date further.
Need help to index them with stock_date.
possible solution.
// first index grouped by product_id
$original = Model::select('column1', 'product_id', 'stock_date')
->where('some condition')
->get()
->groupBy->product_id;
$final = collect();
// iterate through each group and
// group inner collection with 'stock_date'
// and put them back in an collecion
foreach($original as $key => $value) {
$final->put($key, $value->groupBy->stock_date);
}
Do you means these records are nested by stock_date,
and then stock_dates are nested by product_id
If it is, please try this below, the collect() method make all nested records becomes collection, you don't need to use collect() again.
$data = Model::select('column1', 'product_id', 'stock_date')
->where('some condition')
->get();
$data = collect($data)->groupBy('product_id');
$nested_products = [];
foreach($data as $product_id => $items) {
$nested_products []= $items->groupBy('stock_date');
}
Or you can try this line, it's more elegant:
collect($data)->groupBy('product_id')->transform(function($item, $k) { return $item->groupBy('stock_date');})

How to search on specific columns with TNTSearch in Laravel?

Below is my model code Product.php.
public $asYouType = true;
public function toSearchableArray()
{
$array = $this->toArray();
// Customize array...
return $array;
}
Controller code
$phones = Product::search($request['phone'])->get();
Now I want to search for products from my product table, but TNTSearch is searching all columns in my tables and gives me the result. However, I am working on an e-commerce site, and I want results by product title and then from the description column.
My table structure looks like the below image.
For indexing specific columns you should set custom array,
For instance:
public function toSearchableArray()
{
$array = [
//'title' => $this->title,
'description' => $this->description
];
return $array;
}
In above example we ignore the title field content to indexing and just index description field.

Laravel Copy record and duplicate with new values

How can i copy a record and save it with a different value for 1 or more field?
for example:
get----> first_name, last_name, civil_status, work
i want to copy the first name, and last name then insert it with a new civil status and work.
You could use the replicate method of model like this:
// Retrieve the first task
$task = Task::first();
$newTask = $task->replicate();
$newTask->project_id = 16; // the new project_id
$newTask->save();
You could use replicate method. This will create a new object with the same values except the primary key, and the timestamps. After that you can save your model:
$task = Task::find(1);
$new = $task->replicate();
If you want you could change a property
$new->project = $otherProject;
and then
$new->save();
if you want the new ID, easy:
$newID = $new->id;
You can use replicate() and then update that row:
Model::find(1)->replicate()->save();
$model = Model::find(1);
$model->project_id = $new_project_id;
$model->save();
also you can do like this.
$selected = Model::find(1);
$copy = $selected->replicate()->fill(
[
'project_id' => $new_project_id,
]
);
$copy->save();

How can I get separate value of the array item in the codeigniter

I have a Controller in Codeigniter which has given sample of code
$data = array();
if ($query = $this->product_model -> get_individual_records())
{
$data['records'] = $query;
}
here $data store user_id and market_id fetch from the database
what I want to do is I want to store the user_id stored in the $data array to a separate variable like
$uid = the value that that is stored in the array name $data[]
How can i get separate value of the array item in the codeigniter
Assuming you are getting the records through results() method, you can do like
$data['uid'] = $query-> uid;

get data for current product from custom table magento

I have created custom table and model, I can access all data by this model using this code
$model = Mage::getModel('groupprice/groupprice');
$data = $model->getCollection()->getData();
print_r($data);
I just want to filter data only for current product, foreign key in custom table for product is product_id .
How I can achieve this?
Try this:
$productId = 1;//change to your product id
$collection = Mage::getModel('groupprice/groupprice')->getCollection()
->addFieldToFilter('product_id', $productId);
foreach ($collection as $item) {
//do something with $item
//for example print_r($item) to see all it's data
}

Resources