繁体   English   中英

如何从laravel中的多对多关系中检索多条记录

[英]how to retrieve multiple records from many to many relationship in laravel

提前致谢,我在从多对多关系中检索数据时遇到问题,我有订单,每个订单都有很多产品,我正在分析今天订单中售出的产品数量,但是当我打电话时1 order id an error出现表明关系方法不存在。
订单模型:

 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() 方法,关系和检索今天的订单

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM