John Davidson

php - Some records (not all!) return null from Laravel eloquent relationship

0 comments
Message:


I'm desperate. It's about this model relationship:


   public function customer()
{
return $this->hasOne('App\Models\InvoiceCustomer', 'invoice_id', 'id');
}

When I execute the query, I get three results. Two with the correct relationship of the InvoiceCustomer model, but one result is always customer: null.


Invoice::whereHas(['customer'])->get();

The invoice.id field value is exactly eloquent with invoice_customers.id in the database.


That's the db schema of the two tables:


DB: invoice_customers


Schema::create('invoice_customers', function (Blueprint $table) {
$table->foreignUuid('invoice_id')->references('id')->on('invoices')->cascadeOnDelete();
$table->string('number');
$table->string('salutation');
$table->string('first_name');
$table->string('last_name');
$table->string('street');
$table->string('house_number');
$table->string('postcode');
$table->string('city');
$table->string('email');
$table->timestamps();
});

DB: invoices:


Schema::create('invoices', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('company_id')->references('id')->on('companies')->cascadeOnDelete();
$table->string('number');
$table->string('status');
$table->timestamp('date');
$table->decimal('total');
$table->string('type');
$table->json('additional_data')->default('{}');
$table->timestamps();
});

I hope someone have an idea or maybe had such a problem before.


I am grateful for every answer. If you need anything else, please let me know. Thanks very much!



My Answer:
One possible reason for the customer being null in one of the results could be that there is no corresponding record in the invoice_customers table for that particular invoice.

You can try using a leftJoin instead of a hasOne relationship to see if that helps in fetching all the records, even if there is no corresponding record in the invoice_customers table.

Here is an example of how you can modify your relationship:

php
public function customer()
{
return $this->hasOne('App\Models\InvoiceCustomer', 'invoice_id', 'id');
}


Change it to:

php
public function customer()
{
return $this->leftJoin('invoice_customers', 'invoices.id', '=', 'invoice_customers.invoice_id')
->select('invoice_customers.*');
}


This way, you will get all the records from the invoices table, even if there is no corresponding record in the invoice_customers table.

Hope this helps! Let me know if you have any other questions.

Rate this post

5 of 5 based on 5962 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us