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?
2
Answers
protected $table = 'order_products;
in the model will tell Laravel that theOrder
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-modelsI change my answer after reading your answers below.
Your table relationship is
orders
–order_product
–products
.https://webdevetc.com/blog/laravel-naming-conventions/
under Pivot tables
The way you named your pivot table is already correct.
order_product
is to connectorders
toproducts
in a many-to-many.So i think you can try to do the following.
Inside model Product add this relationship.
And in model Order add the other connection
belongsToMany
accepts 2 parameter, 1st is model destination, and 2nd is table pivot name, in your caseorder_product
.With this , an extra model OrderProduct is optional.
To add a product into order , you can use attach
Or if you have extra fields within pivot table
To query the price
And back to your own query.
No need to add orders() inside Order model.
And load only the first 2 relationship should be enough.
$order->load('clients', 'products');