无法从belongsToMany关系laravel获取表字段

时间:2015-03-15 06:50:48

标签: laravel

我有2个表DealerProduct和DealerProductPayments dealer_products包含id和dealer_id列以及dealer_products_payments表,其中包含id和dealer_products_id列

我拥有属于关系的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;
        }

但它不起作用,有人可以帮忙吗?感谢

1 个答案:

答案 0 :(得分:0)

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

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