【问题标题】:Cannot get table field from belongsToMany relationship laravel无法从 belongsToMany 关系 laravel 获取表字段
【发布时间】:2015-03-15 06:50:48
【问题描述】:

我有 2 个表 DealerProduct 和 DealerProductPayments 带有 id 和dealer_id 列的dealer_products 和带有id 和dealer_products_id 列的dealer_products_payments 表

我有 DealerProductPayment 模型与属于关系

public function dealerproduct() {
        return $this->belongsToMany('DealerProduct','dealer_product_payments','dealer_product_id','id');
    }

我试图从 belongsToMany 关系中获取dealer_id

$dealerProductPayment = DealerProductPayment::all();
        foreach ($dealerProductPayment as $payment) {
            echo $payment->dealerproduct->dealer_id;
        }

但它不起作用,有人可以帮我解决这个问题吗?谢谢

【问题讨论】:

    标签: laravel


    【解决方案1】:

    $payment->dealerproduct 的返回值将是一个集合,因为您将关系声明为belongsToMany。从某种意义上说,一次付款属于多个产品,因此,您在$payment->dealerproduct时会得到一个产品列表。

    foreach ($dealerProductPayment as $payment) {
        foreach ($payment->dealerproduct as $dealerproduct) {
            echo $dealerproduct->dealer_id;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-22
      • 2021-07-28
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多