mercredi 28 février 2018

how to retrieve multiple records from many to many relationship in laravel

thanks in advance, i have a problem with retrieving data from many to many relationship, i have orders and every order has many products, and i'm making an analysis aboat how many products sold in today's orders but when i'm calling more than 1 order id an error appears says that the relationship method dosen't exist.
orders model:

 class orders extends Model {
  protected $table = 'orders';
  public $timestamps = false;
  protected $fillable = [
    'serial', 'clientName', 'phone', 'cost', 'notes', 'received_by', 'received_at'
  ];
  public function product() {
    return $this->belongsToMany('\App\Products', 'order_product', 'order_id', 'product_id')->withPivot('product_id', 'count');
  }
}

products model:

class Products extends Model {
  protected $table = 'products';
  public $timestamps = false;
  protected $fillable = [
    'name', 'cost', 'available', 'notes', 'created_at'
  ];
  public function order() {
    return $this->belongsToMany('\App\Orders', 'order_product', 'product_id', 'order_id')->withPivot('order_id', 'product_id', 'count');
  }
}


and here is the controller

$today_orders = Orders::where('received_at', '>=', Carbon::today()->startOfDay())->where('received_at', '<=', Carbon::today()->endOfDay());
$today_orders_ids = array();
foreach($today_orders->get() as $order) {
   array_push($today_orders_ids, $order->id);
}
$today_orders_products = Orders::find($today_orders_ids)->product()->get();

the error message:

BadMethodCallException
Method product does not exist.

is there is an error in my code ? or i can't get multiple records from a relationship
note:

everything works perfectly until the find() method, both the relationship and retrieving today orders



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire