【问题标题】:how to access data of table having two foreign keys in laravel如何在laravel中访问具有两个外键的表的数据
【发布时间】:2020-01-15 09:13:00
【问题描述】:

我有一个名为 order_details 的表,它有两个外键。 (1.) order_id (2.) product_id

在我看来,我已经压缩了整张桌子。当我访问与订单相关的记录时,它们运行良好,但是当我尝试访问 order_detail 表中作为 product_id 的外国产品记录时,我得到空值。

订单详情表:

Schema::create('order_details', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('order_id');
            $table->foreign('order_id')->references('id')->on('orders');
            $table->unsignedBigInteger('product_id');
            $table->foreign('product_id')->references('id')->on('products');
            $table->integer('quantity');
            $table->integer('amount');

            $table->timestamps();
        });

OrderDetail的模型:

 public function order(){
        return $this->belongsTo(Order::class);
    }
    public function products(){
        return $this->hasMany(Product::class);
    }

订单模型:

 public function orderDetails(){
        return $this->hasMany(OrderDetail::class);
    }

产品型号:

 public function orderDetail(){
        return $this->belongsTo(OrderDetail::class);
    }

在我的视图中,我已经在 $orderDetails 中压缩了整个表格。当我尝试像这样访问 Order 表的数据时:

$orderDetails[0]->Order['total_ammount']

它工作正常,因为它通过 order_id 访问订单模型。但以同样的方式,我尝试使用这样的 product_id 从产品模型中获取数据

$orderDetails[0]->Product['name']

它显示我没有错误但为空。

【问题讨论】:

    标签: mysql laravel-5 eloquent


    【解决方案1】:

    你能试着纠正这些关系吗

    订单详情模型

    // individual row of order_details belongs to single product
    public function product(){
        return $this->belongsTo(Product::class);
    }
    

    产品模型到 OrderDetail

    我认为不需要这种关系,因为它必须通过用户模型。即使将其更正为

    public function orderDetails() {
        return $this->hasMany(OrderDetail::class);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2013-03-16
      • 2017-01-23
      相关资源
      最近更新 更多