Laravel many to many need column from join table - laravel

My two tables have relation in this way
public function orders() {
return $this->belongsToMany('App\Order');
}
public function products() {
return $this->belongsToMany('App\Product', 'OrderDetails');
}
How can i get column for quantity? Is defined on order_product table

Use withPivot():
public function orders() {
return $this->belongsToMany('App\Order')->withPivot('quantity');
}
$orders = Product::find($id)->orders;
foreach($orders as $order) {
// $order->pivot->quantity
}

Related

laravel "->ofMany()" for many-to-many pivot (belongsToMany) relationship

For a user with many orders (hasMany relationship), I can use hasOne with ofMany(), e.g.
public function orders()
{
return $this->hasMany(Order::class);
}
public function largestOrder()
{
return $this->hasOne(Order::class)->ofMany('price', 'max');
}
How can I achieve the same for a many to many relationship?
E.g. a product can have many categories (and each category has a weight),
and I want to get the products and their preferred category (=max weight).
// Product
public function categories() {
return $this->belongsToMany(Category::class);
}
// Category
public function products() {
return $this->belongsToMany(Product::class);
}
The following does not work:
// Product
public function preferredCategory() {
return $this->hasOne(Category::class)->ofMany('weight','max');
}
// Product::where('id',1)->with('preferredCategory')
// Column not found: 1054 Unknown column 'categories.product_id'
Suggestions? Using Laravel 9.

Laravel How To Update Nested createMany

Been having a hard time on figuring out how to implement updating records on a nested createMany based on the store method. I have these models and relations:
User Model:
class User extends Model
{
public function orders() {
return $this->hasMany(Order::class);
}
}
Order Model:
class Order extends Model
{
public function user() {
return $this->belongsTo(User::class);
}
public function subOrders() {
return $this->hasMany(SubOrder::class);
}
}
SubOrder Model:
class SubOrder extends Model
{
public function order() {
return $this->belongsTo(Order::class);
}
public function subOrderProducts() {
return $this->hasMany(SubOrderProducts::class);
}
}
SubOrderProducts Model:
class SubOrderProducts extends Model
{
public function subOrder() {
return $this->belongsTo(SubOrder::class);
}
}
Here are the tables:
orders table:
id name
sub_orders table:
id order_id date price
sub_order_products table:
id sub_orders_id product_id
Then on the store method:
public function store(StoreOrderRequest $request) {
$order = auth()->user()->orders()->create($request->validated());
$order_subs = $order->subOrders()->createMany($request->orders);
$order_sub_products = $request->only('subproducts');
foreach ($order_subs as $key => $value) {
$order_sub->subOrderProducts()->createMany($order_sub_products[$key]['products']);
}
}
What I wanted to achieve is to update or create those sub orders and sub order products. If the sub order is already existing, then update, otherwise create a new record with those corresponding sub order products.
Here's what I've tried so far:
public function store(UpdateOrderRequest $request, Order $order) {
$order->update($request->validated());
$order_subs = $order->subOrders()->updateMany($request->orders);
$order_sub_products = $request->only('subproducts');
foreach ($order_subs as $key => $value) {
$order_sub->subOrderProducts()->updateMany($order_sub_products[$key]['products']);
}
}
It's not working as expected since the order subs is only a single record. What's the best way or the right process for updating/creating these records? Thanks.

How to access a relationship through another relationship

I am working on a survey system and I have a problem accessing one relationship through another.
I have these models and these relationships
Post
id
survey_id
public function survey()
{
return $this->belongsTo(Survey::class);
}
Surveys
id
survey_type_id
public function surveyOptions()
{
return $this->belongsToMany(Survey_options::class);
}
public function surveyType()
{
return $this->belongsTo(Survey_type::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
Survey_types
id
public function surveyOptions()
{
return $this->belongsToMany(Survey_options::class);
}
Survey_options
id
survey_type_id
public function values()
{
return $this->hasMany(Option_value::class);
}
options_values
survey_options_id
survey_id
public function surveyOptions()
{
return $this->belongsTo(Survey_options::class);
}
Survey_Survey_options (pivot)
survey_id
survey_options_id
I need to do a query with eadger loading to bring me all the posts with survey, surveyOptions, withCount comments y options_values of each surveyOptions. Something like this:
$post->survey->surveyOptions->options_values_count
I have managed to create this query that works for me everything except fetching the option_values count from each SurveyOption. How can I do it?
$posts = Post::with([
'survey' => function ($query) {
$query->withCount('totalSurveys');
},
'survey.surveyOptions',
'image',
'categories'
])
->withCount('comments')
->get();

Eloquent query on tables with relationships and a condition in a pivot table

I've various tables with these relationships, described as models
Customers
class Customers extends Model
{
public function claims()
{
return $this->hasMany(Claims::class);
}
}
Claims
class Claims extends Model
{
public function refunds()
{
return $this->hasMany(Refunds::class);
}
public function customers()
{
return $this->belongsTo(Customers::class,'customers_id');
}
}
Refunds
class Refunds extends Model
{
public function services()
{
return $this->belongsToMany(Services::class)
->withPivot(['services_id','services_amount','services_status']);
}
public function claims()
{
return $this->belongsTo(Claims::class,'claims_id');
}
}
Services
class Services extends Model
{
public function refunds()
{
return $this->belongsToMany(Refunds::class);
}
}
I need to do a query that return all rows from Customers with a row count on the pivot table refunds_services where services_id = 1 for each Customers row.
How can I do this? Is it possible? or better i use query builder and sql with several joins
Thx
you can try :
Customers::select('cliente')
->addSelect([
'countRefundService' => Customers::withCount('claims.refunds.services', function($query) {
$query->where('id', 1);
})->get();
])
->whereHas('claims.refunds.services', function ($query) {
$query->where('id', 1);
} )
->get();

Reach the subcategory from the Product model (Laravel)

I am trying to reach the last laravel model from the first one with eloquent relationships. How can I reach the Subcategory directly from Product?
The 3 Models I have:
Product (id, category_id, etc..)
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
Category (id, name)
public function products()
{
return $this->hasMany('App\Product', 'category_id');
}
public function sub_categories()
{
return $this->hasMany('App\SubCategory', 'category_id');
}
SubCategory (id, category_id, name)
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
I would've assumed I could reach it with
Product::find(1)->categories->sub_categories;
Am I missing something obvious here?
read this docs
Product
class Product extends Model
{
public function SubCategory()
{
return $this->hasManyThrough('App\Category', 'App\SubCategory');
}
}
In Addition add the subCategories method on Product model and also a product is belongs to a category not categories
and also always try to use camel case for the methods (subCategories)
replace your code with this
Product:
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
public function subCategories()
{
return $this->category()->subCategories;
}
Category:
public function products()
{
return $this->hasMany('App\Product', 'category_id');
}
public function subCategories()
{
return $this->hasMany('App\SubCategory', 'category_id');
}
SubCategory:
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
finally use this to get the subcategories
Product::find(1)->subCategories;
Product::find(1)->categories is an array. You will have to loop it to get the subcategory of each category. See below
$categories = Product::find(1)->categories;
foreach ($categories as $category {
//Get subcategories for each category
dump($category->sub_categories);
}

Resources