Home > database >  Model file name changes the table name in database
Model file name changes the table name in database

Time:02-01

Hello i have a table called order_product that i want to get values from it and the model for that table called order_product with values:

public $timestamps = false;

    protected $fillable = [
        'order_id',
        'product_id',
        'amount',
    ];

This is the code of the model Order :

public $timestamps = true;

    protected $fillable = [
        'order_number',
        'client_id',
        'description',
    ];


    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function products()
    {
        return $this->belongsToMany(Product::class);
    }

    public function orders()
    {
        return $this->belongsToMany(order_product::class);
    }

A professional guy helped me and explained to me how the relation worked so the client and products work very good but the orders makes error in the sql.

This is the code im executing in the controller:

$orders = Order::where('id', $id)->firstOrFail();
$orders->load('client', 'products','orders');

The error that i get is:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'user_project_db.order_products' doesn't exist

What should be the name of the file order_product so the query can execute properly?

CodePudding user response:

protected $table = 'order_products; in the model will tell Laravel that the Order model's data is stored in a table by that name.

However, typically you'd have an Order model, a Products model, and a pivot table (potentially with a pivot model, if you need it) titled order_products. https://laravel.com/docs/9.x/eloquent-relationships#defining-custom-intermediate-table-models

CodePudding user response:

Personally I write the model name always in CapitalCase.

It is also the laravel standard
For example when you generate new model while making migration
php artisan make:migration create_order_products_table --model
a CapitalCase named model will be auto generated called OrderProduct
and placed inside ./app/Models/OrderProduct.php

https://webdevetc.com/blog/laravel-naming-conventions/

So in your case for tabel order_products(try to use multiple format)
best to write your model as OrderProduct (single format)

Also inside the model you can add protected $table = 'order_products';

public function orders()
{
    return $this->belongsToMany(OrderProduct::class);
}

I hope this can help you out.

extra note: if it does not work , try to clear your cache
php artisan optimize:clear

  • Related