lepikhinb / laravel-fluent

MIT License
549 stars 25 forks source link

Using BelongsTo relation correctly? #18

Open christhomas opened 2 years ago

christhomas commented 2 years ago

Hi! Firstly thanks for this amazing library, I love that I can now write properties into the class and it'll help autocomplete on eloquent models!

I'm having a doubt whether I'm using BelongsTo relation correctly, I've also noticed in your tests that you are sometimes using the BelongsTo attribute and then sometimes using a typical Laravel `function products(): BelongsTo" style function, is the BelongsTo attribute not working as expected sometimes?

This is what I've got in my class

class InvoicePosition {
    #[BelongsTo('invoice_id', 'id')]
    public Invoice $invoice;
}

The InvoicePosition table has a foreign key "invoice_id" to the Invoice table with the primary key "id", but when I try to set the Invoice and then call save(), I get this error back

I do this in my code

$invoice = new Invoice([...attrs];
$invoice->save();

$position = new InvoicePosition([...attrs]);
$position->invoice = $invoice;
$position->save();
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

and then in the returned query I get back with the error, the invoice_id field is not being set on the query, so that's pretty clear why it's not working, but I'm not sure what information that I'm missing to get it working.

I've seen your tests use the default eloquent style of handling belongsTo as well, so I was wondering about whether this is still a WIP or it does actually update foreign relations for you correctly.

Thanks!

hsmfawaz commented 2 years ago

if you used this style

#[BelongsTo('invoice_id', 'id')]
public Invoice $invoice;

$position->invoice //will use the invoice class
$position->invoice() // but the relation will not work

You should use this style if you want to work with relations correclty

#[Relation]
public Invoice $invoice;

public function invoice(){
     return $this->belongsTo(Invoice::class);
}