How to create seeding hierarchy in laravel - laravel

I have problem creating a seeding hierarchy in Laravel, is there way i can achieve hierarchy by just creating a seeding data. I have 3 column [Vehicle,Model,Variant] so each vehicle has different model and variant. I will show you the sample table that I created on excel that I wanted to achieve.
Expected Output:
Here is my seeding function:
<?php
use Illuminate\Database\Seeder;
use App\Variant;
use App\Vehicle;
use App\VehicleModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class CarsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
foreach (Vehicle::all() as $vehicle_data) {
foreach (VehicleModel::all() as $vehicle_model_data) {
foreach (Variant::all() as $variants_data) {
DB::table('cars')->insert([
[
'make' => $vehicle_data->name,
'model_id' => $vehicle_model_data->id,
'variant_id' => $variants_data->id,
'created_at'=>date('Y-m-d H:i:s'),
'updated_at'=>date('Y-m-d H:i:s')
]
]);
}
}
}
}
}
Car Model:
class Car extends Model
{
//
protected $table = 'cars';
protected $fillable = [
'id',
'make',
'variant_id',
'model_id'
];
public function variants() {
return $this->hasMany('App\Variant','id','variant_id');
}
public function models() {
return $this->hasMany('App\VehicleModel','id','model_id');
}
}
Variant Model:
class Variant extends Model
{
//
protected $table = 'variants';
protected $fillable = [
'name'
];
}
Vehicle Model:
class Vehicle extends Model
{
//
protected $table = 'vehicles';
protected $fillable = [
'name'
];
}
Vehicle Model:
class VehicleModel extends Model
{
//
protected $table = 'vehicle_models';
protected $fillable = [
'name'
];
}

Assuming the following relations
Vehicle hasMany VehicleModel(s)
VehicleModel hasMany Variant(s)
class Vehicle extends Model
{
public function vehicle_models()
{
return $this->hasMany(VehicleModel::class);
}
}
class VehicleModel extends Model
{
public function variants()
{
return $this->hasMany(Variant::class);
}
}
Try this
public function run()
{
$vehicles = Vehicle::with('vehicle_models.variants')->get();
foreach($vehicles as $vehicle) {
foreach($vehicle->vehicle_models as $model) {
foreach($model->variants as $variant){
Car::create([
'make' => $vehicle->name,
'model_id' => $model->id,
'variant_id' => $variant->id
]);
}
}
}
}

Related

Astrotomic Translatable - pivot column - Laravel 9

I'm having trouble translating a pivot column.
I've been trying all day to add this translation but it still doesn't work.
I'm using the package: https://github.com/Astrotomic/laravel-translatable
Plain tables work fine, but pivot doesn't.
My code (the naming was quick, as the code will work, I'm going to refactor it):
class Offer extends Model implements TranslatableContract
use HasFactory, Translatable;
public array $translatedAttributes = [
'name',
'description'
];
public function attributes(): BelongsToMany
{
return $this->belongsToMany(Attribute::class, 'attribute_offer')->using(AttributeOffer::class)->withTimestamps();
}
class Attribute extends Model implements TranslatableContract
{
use HasFactory, Translatable;
public array $translatedAttributes = [
'name',
];
public function values(): BelongsToMany
{
return $this->belongsToMany(Offer::class, 'attribute_offer', 'attribute_id', 'offer_id')->using(AttributeOffer::class);
}
class AttributeOffer extends Pivot implements TranslatableContract
{
use Translatable;
public $incrementing = true;
public array $translatedAttributes = [
'content',
];
protected $fillable = [
'attribute_id',
'offer_id',
];
}
class AttributeOfferTranslation extends Model
{
protected $table = 'attribute_offer_translations';
public $timestamps = false;
protected $fillable = [
'content',
];
}
class OfferController extends Controller
{
private function updateAttributeValues($offer, $attributes)
{
foreach ($attributes as $slug => $values) {
$pivot = $offer->attributes()->whereSlug($slug)->first()->pivot;
foreach ($values as $locale => $value) {
$pivot->translate($locale)->content = $value;
}
}
}
The structure of the attributes is:
[
'test' =>[
'en' => 'test',
'es' => 'test',
'de' => 'test',
],
'test2' =>[
'en'=> 'test',
'es'=> 'test',
'de' => 'test',
],
]
Unfortunately pivot->translate() always returns null.
Also, when I manually add transactions to the database, it does not display it.
I will be very grateful for help with this translation.
Okay, I fixed it like this, only I have to pass id instead of slugs.
class Offer extends Model implements TranslatableContract
{
...
public function attributeValues(): HasMany
{
return $this->hasMany(AttributeOffer::class);
}
}
class AttributeOffer extends Pivot implements TranslatableContract
{
...
protected $translationForeignKey = 'attribute_offer_id';
...
}
private function updateAttributeValues($offer, $attributes)
{
foreach ($attributes as $id => $values) {
$offer->attributeValues()->whereAttributeId($id)->first()->update($values);
}
}

Laravel TypeError in many to many relationship

I have 3 models: Order, Products, OrderProducts:
class Order extends Model
{
use HasFactory;
protected $fillable = [
'name',
];
public function products(){
return $this->belongsToMany(OrderProduct::class);
}
}
class Products extends Model
{
use HasFactory;
protected $fillable = [
'name', 'link', 'buyprice', 'sellprice','weight',
];
public function orders(){
return $this->belongsToMany(OrderProduct::class);
}
}
class OrderProduct extends Model
{
use HasFactory;
protected $fillable = [
'order_id', 'product_id',
];
public function orders() {
return $this->belongsToMany(Order::class);
}
public function products() {
return $this->belongsToMany(Products::class);
}
}
When i view a specific Order i want to display all associated products, which i try to retrieve like this in my controller:
public function show($id)
{
//$products = Products::all();
$order = Order::where('id',$id)->first();
$orderList = $order->products();
return $orderList;
}
The error i get it:
TypeError
Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given, called in D:\laravel\pricing\vendor\laravel\framework\src\Illuminate\Http\Response.php on line 72
How can i get collection of all products for a specific order?

incorrect table name inserting into using Laravel Excel to Collection

I'm attemptng to insert relational data using the Laravel Excel concern ToCollection
use Maatwebsite\Excel\Concerns\ToCollection;
however the query is attempting to insert into the table objective_years and not objective_year
ObjectivesImport.php
namespace App\Imports;
use App\Models\Objective;
use App\Models\ObjectiveYear;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;
class ObjectivesImport implements ToCollection
{
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
$objectiveDetail = Objective::create([
'description' => $row[0],
'guidance' => $row[1],
'team_id' => $row[2],
'subject_id' => $row[3],
]);
$yearDetail = ObjectiveYear::create([
'objective_id' => $row[4],
'year_id' => $row[5],
]);
}
}
}
I have two models with a many to many relatinship pivot.
Objective
class Objective extends Model
{
use HasFactory;
protected $fillable = [
'description', 'guidance','subject_id','team_id'
];
public function years ()
{
return $this->belongsToMany('App\Models\Year');
}
}
Year
class Year extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
public function objectives()
{
return $this->belongsToMany('App\Models\Objective')->withTimestamps();
}
}
ObjectiveYear
class ObjectiveYear extends Model
{
use HasFactory;
protected $fillable = [
'objective_id', 'year_id'
];
}
Controller
class ImportController extends Controller
{
public function getImport()
{
return view('import');
}
public function import()
{
Excel::import(new ObjectivesImport, request()->file('csv_file'));
return redirect('/')->with('success', 'All good!');
}
}

Search in Laravel relation using json column

I have problem with search in json column.
I have 3 relations:
products
feature products
feature_values
My tables:
products: https://ibb.co/1dgjT6m
feature products: https://ibb.co/K9f74Wn
feature_values: https://ibb.co/rc3zG5W
My migrations:
Product:
class Product extends Model implements Presentable
{
....
public function featureProducts()
{
return $this->hasMany(FeatureProduct::class, 'product_id');
//return $this->belongsToMany(Feature::class, 'feature_product', 'id');
}
}
FeatureProduct
class FeatureProduct extends Model
{
protected $table = "feature_product";
protected $with = [
'values'
];
public function values()
{
return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
}
}
FeatureValues:
class FeatureValue extends Model
{
use SoftDeletes,
Translatable;
protected $fillable = [
'feature_id',
'value'
];
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
protected $translatable = [
'value'
];
public function feature(): BelongsTo
{
return $this->belongsTo(Feature::class);
}
public function getAdminUrlAttribute(): AbstractAdminUrlPresenter
{
return new FeatureValueUrlPresenter($this);
}
}
I need to show products with features and assigned features_values
I heve problem with search in json column: feature_product. feature_values_ids
When I have INT in this column, then this is working fine:
public function values()
{
return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
}
When I have:
["1", "2","3"]
I haven't any results :(
Haw can I repair it?

RelationNotFoundException in RelationNotFoundException.php

each product hasMany property.
when I use with function:
dd(Product::with(ProductProperty::class)->get());
I got this error :
RelationNotFoundException in RelationNotFoundException.php
Call to undefined relationship [App\Models\ProductProperty] on model [App\Models\Product].
class Product extends Model
{
protected $table = 'products';
protected $fillable = [
'user_id' ,'brand_id' , 'title', 'price', 'current_buy','max_buy','min_buy_per_bill',
'max_buy_per_bill','count','off','seri','short_description','long_description',
];
public function ProductProperty()
{
return $this->hasMany('App\Models\ProductProperty');
}
}
class ProductProperty extends Model
{
protected $table = 'products_properties';
protected $fillable = [
'product_id' ,'parent_id' , 'title','value', 'price', 'current_buy','max_buy','min_buy_per_bill',
'max_buy_per_bill','count','off','seri','short_description','long_description',
];
public function Product()
{
return $this->belongsTo('App\Models\Product');
}
}
Looking at your code you can't use ::class with the with() function. The main reason is the ::class will return the full path with namespace.
Product::with(ProductProperty::class)->get(); is incorrect.
Replace it with Product::with('ProductProperty')->get();

Resources