如何在laravel中从多对多关系中检索多个记录

时间:2018-02-28 17:35:23

标签: php laravel-5 eloquent many-to-many relationship

事先感谢,我有从多对多关系中检索数据的问题,我有订单,每个订单都有很多产品,而且我正在分析当今销售的产品数量。订单,但是当我调用超过1个订单ID时,会出现错误,表示关系方法已存在。
订单型号:

 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');
  }
}

产品型号:

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');
  }
}


这是控制器

$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();

错误消息:

BadMethodCallException
Method product does not exist.

我的代码中是否有错误?或者我无法从关系中获得多条记录 注意:

  

一切都完美无缺,直到find()方法,两者都有   关系和检索今天的订单

1 个答案:

答案 0 :(得分:0)

用控制器替换控制器中的第2-5行:

$today_orders = $today_orders->with('product')->get();
$today_orders_products = $today_orders->pluck('product')->collapse();