【问题标题】:how to use model in laravel to get value?如何在 laravel 中使用模型来获取价值?
【发布时间】:2021-04-14 23:15:27
【问题描述】:

我有 3 个表 Orders 、 Orderdetails 和 products 表,每个订单都是唯一的,每个订单都有多个带有订单 ID 的 orderdetail,每个 orderdetail 都有 product_id

我在刀片中使用 foreach 循环

 @foreach($order->orderdetail as $odetail)
  <tr>
    <td><input type="number" value="{{ $odetail->amount }}" ></td>
   </tr>
    @endforeach

this value="{{ $odetail-&gt;amount }}" 在输入字段中获取值 25

我还有另一个 foreach 循环

 @foreach($products as $key => $p)
  <tr>
    <td><input type="number" value="{{ $p->order->orderdetail->unit }}"></td>
   </tr>
    @endforeach

我希望上面的循环 value="{{ $odetail-&gt;amount }}" 在第二个 foreach 循环中输出,所以我试试这个

value="{{ $p->order->orderdetail->unit }}" 

如果 orderdetail 在第一个循环中获得价值,那么为什么它在第二个 foreach 循环中没有获得价值,有人可以告诉我什么是错误以及 doeas 模型如何工作以及我如何在第二个循环中获得价值?

这是我的 Order 模型类和 orderdetail 函数

class Order extends Model
{
    public function orderdetail(){
            return $this->hasMany('App\OrderDetail','order_id');
        }
}

这是我的 orderdetail 类和函数

class OrderDetail extends Model
{    
    public function order(){
        return $this->belongsTo('App\Order');
    }

    public function product(){
        return $this->belongsTo('App\Product');
    }
}

这里是产品型号

class Product extends Model
{
    public function category(){
        return $this->belongsTo('App\Category');
    }
}

orderdetai 的数据库图像 enter image description here

【问题讨论】:

  • 您能否分享一下您的模型,包括“单位”字段。但一个广泛的假设是您的单位字段也是一个关系字段,因此无法直接输出集合。
  • 请显示您正在获取数据的模型查询表单
  • 输入dd($products)并查看那里的记录
  • 可以分享一下产品型号吗?
  • 感谢每一位贡献者,我用所有使用的模型更新了代码

标签: php laravel model-view-controller eloquent laravel-blade


【解决方案1】:

看来您只是错过了Product 模型中的order 关系

public function orders(){ // by laravel convention you need a plural name for hasMany relation
    return $this->hasMany('App\order','product_id');
}

希望它能解决你的问题。

【讨论】:

  • 在订单表中我没有使用 order_id 我只有 id 所以当我通过 hasMany('App\Order','id');它给了我错误 [orderdetail] 不存在
  • 我的错。我已经改变了答案。应该有product_id 而不是order_id
猜你喜欢
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 2023-01-05
  • 2019-12-26
  • 1970-01-01
  • 2019-04-17
  • 2020-04-04
  • 1970-01-01
相关资源
最近更新 更多