How to get product name from pivot table using laravel? - laravel

I am trying to get product name from pivot table but unfortunately i have no idea how can i get product name from pivot table please help me thanks.
Product Model
public function category()
{
return $this->belongsToMany('App\ProductCategory', 'product_category', 'product_id', 'mf_product_category_id');
}
productcategory model
public function products()
{
return $this->belongsToMany('App\Product', 'product_category', 'mf_product_category_id', 'product_id');
}
controller
public function getproduct(Request $request)
{
// getting category Id
$categoryId = $request->category;
// getting product Id
$name = trim($request->product);
$productId = Product::where('name', $name)->pluck('id');
$getProductcategory = ProductCategoryCount::whereIn('mf_product_category_id', $categoryId)->whereIn('product_id', $productId)->get();
return $getProductcategory;
// return response()->json($getproduct);
}

As stated in laravel doc, you can retrieve pivot table extra data using withPivot on the relationship.
Define category in the Product Model
public function category()
{
return $this->belongsToMany('App\ProductCategory', 'product_category', 'product_id', 'mf_product_category_id')
->withPivot('Your_extra_data_on_pivot_table');
}
And by querying products, you can get category (which I suggest to be categories). You can retrieve it like this $products->first()->pivot->{name of_your_extra_data_on_pivot_table}
It is more optimized if you eager load this relationship.

Related

Model file name changes the table name in database

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?
I 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 connect orders to products in a many-to-many.
So i think you can try to do the following.
Inside model Product add this relationship.
public function orders()
{
return $this->belongsToMany(Order::class, 'order_product');
}
And in model Order add the other connection
public function products()
{
return $this->belongsToMany(Product::class, 'order_product');
}
belongsToMany accepts 2 parameter, 1st is model destination, and 2nd is table pivot name, in your case order_product.
With this , an extra model OrderProduct is optional.
To add a product into order , you can use attach
$order = Order::find($order_id);
$order->products()->attach($product_id);
Or if you have extra fields within pivot table
// first implement this change inside Order model
return $this->belongsToMany(Product::class, 'order_product')
->withPivot('price', 'qty');
// to attach for example price and qty
$order->products()->attach($product_id, ['price' => 200', 'qty'=> 1]);
To query the price
$order_product = $order->products()
->where('product_id', $product_id)
->first()->pivot;
$price = $order_product->price;
$qty = $order_product->qty;
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');
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

Laravel apply where clause to belongsToMany query using with() method

I have a products table with brand_id, and a category_products table with, product_id and category_id.
My Products model :
class Product extends Model
{
public function categories() {
return $this->belongsToMany(Category::class)->withTimestamps();
}
}
My Brands Model :
class Brand extends Model
{
public function products() {
return $this->hasMany(Product::class)->with(['categories']);
}
}
My question is, How can I fetch the products from a Brand instance that belongs to certain category?
$brand = App\Brand::find(1);
/*
I want to be able to do something in the likes of :
*/
$brand->products_which_are_under_this_category
Remove with(['categories']) method from inside products() and write a query like that.
$brand->products()->with(['categories' => function ($query) {
$query->where('category_id', CATEGORY_ID);
}])->get();
hope this can help.

Trying to display eloquent data base from ID's

Hi I am trying to create a record base from ID of an order transaction.
I have here the ORDERS, CAMPANIES and CURRENCIES models.
Now I want the ORDER to get the ID from a URL Parameter, and then the companies should grab the company_id from Orders same with currency, I want to grab the currency_id from orders.
Here's what I came up so far:
public function create($order_id)
{
$order = Orders::find($order_id)->where('id', '=', $order_id)->get();
$company = Companies::where('id', '=', $order['company_id'])->get();
$currency = Currencies::where('id', '=', $order['company_id'])->get();
$banks = Banks::all('name','acronym','id')->get();
return view('orderPayments.create', compact('order'))
->with('company', $company)
->with('currency', $currency)
->with('banks', $banks);
}
currencies model
public function orderPayments()
{
return $this->hasMany('App\Orderpayments', 'id','currency_id');
}
Companies Model
public function orderPayments()
{
return $this->hasMany('App\Orderpayments', 'id','company_id');
}
Order Payments Model
public function company()
{
return $this->hasOne('App\Companies', 'id','company_id');
}
public function currency()
{
return $this->hasOne('App\Currencies', 'id', 'currency_id');
}
public function bank()
{
return $this->hasOne('App\Bank', 'id', 'currency_id');
}
How can I achieve it? thank you so much in advance!
UPDATE
I just applied #sandy's answer. I checked if the $order has a content so I echod the $order by doing this, {{ $order }} The return value is ok.
but when I calling the other attributes like $order->grandtotal, or $order->companies->comp_name the error is
If your relationship between your models is a One To Many relationship you should use belongsTo in your relations like this:
OrderPayment Model
public function company()
{
return $this->belongsTo('App\Companies','company_id');
}
public function currency()
{
return $this->belongsTo('App\Currencies','currency_id');
}
public function bank()
{
return $this->belongsTo('App\Bank', 'currency_id');
}
Also, the second parameter on the function should be your foreign key.
Answering your question:
If you want to access the relations of a given Order you could do this:
$order = Order::find($order_id);
$order->company; // this will return the company
$order->currency; // this will return the currency
If you want to display in your view:
{{$order->company->anyCompanyAttribute}}
Note:
You should name your models in SINGULAR like Currency, Company. Not in plural.
try like this
$order = Orders::with(['company','currency'])->where('id', '=', $order_id)->get();

laravel 5 many to many not working

I have a many to many relationship between Products and Categories Table with Pivot table as Product_Category
In Products Model:
public function categories(){
return $this->belongsToMany('\App\Models\Categories', 'product_category', 'product_id', 'category_id');
}
In Categories Model:
public function products(){
return $this->belongsToMany('\App\Models\Products', 'product_category', 'category_id', 'product_id');
}
In Product_Category Model:
public function products(){
return $this->belongsTo('App\Models\Products');
}
public function categories() {
return $this->belongsTo('App\Models\Categories');
}
In ProductController:
$data = Products::with('categories')->select('id','product_name','user_id','created_at')->orderBy('id', 'desc')->paginate(20);
Then i test with function below:
foreach ($data as $val) {
$cats = $val['categories'];
}
I try to var_dump(), but nothing happened:
object(Illuminate\Database\Eloquent\Collection)#472 (1) {
["items":protected]=> array(0) { }
}
Please help me
When you have created a Pivot Model in your application, then This pivot table has a one-to-many relationship with each of your corresponding models. i.e. Product_Category model has a one-to-many relationship with Products and Categories Models. So, code in Products and Categories Models will be like below:
In Products Model:
public function categories(){
return $this->hasMany('\App\Models\ProductCategory', 'category_id');
}
In Categories Model:
public function products(){
return $this->hasMany('\App\Models\ProductCategory','product_id');
}
Do the changes as above and it should be working.

Laravel 4 eloquent

Is there any way I can do this with eloquent?
$orders = Customer::with('orders','orders.shop')->where('orders.shop.location','=','Japan')->get()
Customers, orders and shop are tables where 1 customer has many orders and each order has one shop only.
Location is a column in the shop table
I keep getting an error stating orders.shop.location is a column not found.
Anyone can help? Thanks in advance.
You need to defined relationship in your model classes.
Customer model:
public function orders()
{
return $this->hasMany('Order');
}
Order model:
public function customer()
{
return $this->belongsTo('Customer');
}
Then if you want orders of a special customer you just have to do :
$orders = Customer::find($id)->orders;
Or find the user attatched to an order:
$user = Order::find($id)->user;
You can also use the same kind of relation between your Shop and Order model and do something like this:
$orders = Order::with(array('shop' => function($query)
{
$query->where('location', '=', 'japan');
}))->get();
Which should give you all orders for a shop located in japan.
More informations about this type of request:
http://laravel.com/docs/eloquent#eager-loading
in CostumerModel you need set a relationship (One To Many):
public function order()
{
return $this->hasMany('OrderModel', 'foreign_key_in_orderTable');
}
in OrderModel too:
public function costumer()
{
return $this->belongsTo('CostumerModel', 'foreign_key_in_orderTable');
}
then in OrderModel one more relationship with Shop (One To One):
public function shop()
{
return $this->hasOne('ShopModel', 'foreign_key');
}
Now in ShopModel (One To One):
public function order()
{
return $this->belongsTo('OrderModel', 'local_key');
}
query:
$orders = Customer::with('costumer', 'shop')->where('location','=','Japan')->get();

Resources