gpt4 book ai didi

mysql - 如何在laravel中访问具有两个外键的表的数据

转载 作者:行者123 更新时间:2023-11-29 15:14:55 25 4
gpt4 key购买 nike

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

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

订单详细信息表:

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

订单详细信息的模型:

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

我已经在我的 View 中压缩了 $orderDetails 中的整个表。当我尝试像这样访问订单表的数据时:

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

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

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

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

最佳答案

你能尝试纠正这些关系吗

订单详细信息模型

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

产品型号到订单详细信息

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

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

关于mysql - 如何在laravel中访问具有两个外键的表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59748156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com