0
votes

I have a next models:

class Product extends Model{
    protected $table = 'products';

    public function payments()
    {
        return $this->belongsToMany('App\Payment', 'payment_product', 'product_id', 'payment_id')
    }
}

class Payment extends Model{
    protected $table = 'payments';

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

Pivot table: payment_product(id, product_id, payment_id)

Eloquent

 public function details($id){
        $product = Product::with('payments')->find($id);
        dd($product->payments); // return null
        return view('products.details', ['product' => $product]);
    }

I need to bring in a foreach, but $product->payments is null. Why is that ? All the tables are not empty.

UPD Sub query $this->belongsToMany('App\Payment', 'payment_product', 'product_id', 'payment_id'); Results:

enter image description here

3
Just an FYI, because you're following laravel's naming convention you don't have to provide the table names/columns in your relationships.Rwd

3 Answers

1
votes

try:

public function payments()
{
    return $this->belongsToMany('App\Payment', 'payment_product', 'payment_id', 'product_id')
}

I think you have your FK in the wrong order.

In fact, I don't think you need to specify anything more than:

public function payments()
{
    return $this->belongsToMany('App\Payment')
}
1
votes

Looks like you are joining two tables based on unrelated fields.

When you do

return $this->belongsToMany('App\Payment', 'payment_product', 'product_id', 'payment_id')

your table products gets inner joined with payment_product on
products.product_id = payment_product.payment_id. But I think these two columns are not the related keys. Instead, in your payment_product, join with the product_id in this table with products.product_id. That might work.

0
votes

Rename payments to payments_method:

public function payments_method(){
   return $this->belongsToMany('App\Payment'); //or ('App\Payment', 'payment_product', 'payment_id', 'product_id') 
}

 $product = Product::find($id);
 $product->payments_method; //this is work

This is magic:)