I have the following three table in laravel app
purchases table
id, name, price
Products table
id, purchase_id, price
sales table
id, product_id, quantity, total-price
The sales table belongs to products table refers product id while products table belong to purchases table refers purchase id
Now i I want to fetch data in sales tables but also in need the name of the product which come from purchases table the final results must be
new table
id, product_id, quantity, total-price, name
my query below fetch only sales table data
$sales = Sales::whereBetween(DB::raw('DATE(created_at)'), array($from_date, $to_date))->get();
here I return yajira datatable
return Datatables::of($sales)->addIndexColumn()->make(true);
other code in models
sales model
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
public function purchase()
{
return $this->belongsTo(Purchase::class,'purchase_id');
}
products model
public function purchase()
{
return $this->belongsTo(Purchase::class);
}
purchases model
public function category()
{
return $this->belongsTo(Category::class);
}
public function supplier()
{
return $this->belongsTo(Supplier::class);
}
2
Answers
You need to do join operation for this.
You can learn more from the documentation
You just need to define your relationships properly. The
Sales
model should be related to thePurchases
table with a has-one-through relationship. Then it’s a simple matter of eager loading the relationship.And there’s no need to use a raw query in the controller as long as your 2 date variables are correct:
On the front end, the data will be available through
purchase.name
.